Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7180659
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T17:23:42+00:00 2026-05-28T17:23:42+00:00

I am making a TCP chat server from a simple tutorial I found and

  • 0

I am making a TCP chat server from a simple tutorial I found and I’m kind of new to java. I will eventually make a client class but I’ve been testing it through telnet so far. I have a couple of problems. I have setup the server to take commands from the client. For example “EXIT” which closes the client connection, and “Username” which prints “OK”. Shown below:

USER 1: TIM

Welcome to Bob's Chat Server!

Please Enter a User Name: 
Tim
Welcome Tim we hope you enjoy your chat today
Bob:Hello
Hi Bob
Tim
OK
EXIT
Closing Connection  . . . Goodbye

USER 2: BOB

Welcome to Bob's Chat Server!

Please Enter a User Name: 
Bob
Welcome Bob we hope you enjoy your chat today
Hello
Tim:Hi Bob
Tim:Tim

I have three problems that I want to address:

  1. You’ll notice that when USER 1 typed “Tim” (his username) it said “OK” like I wanted, but it also printed “Tim” to USER 2. Is there a way to make it not send my typed commands across? So when I type “Tim” it doesn’t print “Tim” to USER 2?

  2. When messages are sent to other users it displays who said it. Is there a way to print the name on both connections? For example when USER 2 says “Hello” it looks more like “Bob: Hello” on both connections?

  3. Is there a way to keep track of everything that’s said in the entire chat session and print off the entire contents of the chat to whatever user requested it?

Here is my server code:

// Chat Server runs at port no. 9020
import java.io.*;
import java.util.*;
import java.net.*;
import static java.lang.System.out;

public class  TCPServer 
{
  Vector<String> users = new Vector<String>();
  Vector<HandleClient> clients = new Vector<HandleClient>();

  int PORT = 9020;
  int NumClients = 10;

  public void process() throws Exception  
  {
      ServerSocket server = new ServerSocket(PORT,NumClients);
      out.println("Server Connected...");
      while( true) 
      {
         Socket client = server.accept();
         HandleClient c = new HandleClient(client);
         clients.add(c);
     }  // end of while
  }

  public static void main(String ... args) throws Exception 
  {
      new TCPServer().process();
  } // end of main

  public void boradcast(String user, String message)  
  {
        // send message to all connected users
        for (HandleClient c : clients)
           if (!c.getUserName().equals(user))
           {
              c.sendMessage(user,message);
           }
  }

  class HandleClient extends Thread 
  {
    String name = "";
    BufferedReader input;
    PrintWriter output;

    public HandleClient(Socket client) throws Exception 
    {
          // get input and output streams
         input = new BufferedReader(new InputStreamReader(client.getInputStream())) ;
         output = new PrintWriter (client.getOutputStream(),true);
         output.println("Welcome to Bob's Chat Server!\n");
         // read name
         output.println("Please Enter a User Name: ");
         name  = input.readLine();
         users.add(name); // add to vector
         output.println("Welcome "+name+" we hope you enjoy your chat today");
         start();
    }

    public void sendMessage(String uname,String  msg)  
    {
        output.println( uname + ":" + msg);
    }

    public String getUserName() 
    {  
        return name; 
    }

    public void run()  
    {
         String line;
         try    
         {
            while(true)   
            {
                        line = input.readLine();
                if("EXIT".equals(line))
            {
                output.println("Closing Connection  . . . Goodbye");
                            clients.remove(this);
                        users.remove(name);
                break;
                    }
            else if(name.equals(line))
            {
                            output.println("OK");
                    }
                boradcast(name,line); // method  of outer class - send messages to all
            }// end of while
         } // try
         catch(Exception e) 
         {
           System.out.println(e.getMessage());
         }
    } // end of run()
  } // end of inner class
} // end of Server

Any help is appreciated. Thanks.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T17:23:43+00:00Added an answer on May 28, 2026 at 5:23 pm

    I had modified your code as per your liking , do have a look :

    For Point 1:

    public void run()  
        {
             String line;
             try    
             {
                while(true)   
                {
                            line = input.readLine();
                    if("EXIT".equals(line))
                    {
                        output.println("Closing Connection  . . . Goodbye");
                        clients.remove(this);
                        users.remove(name);
                        break;
                    }
                    else if(name.equals(line))
                    {
                        output.println("OK");
                    }
                    else
                    {
                        // Seems to me just adding this else part will do the trick for point one.
                        boradcast(name,line); // method  of outer class - send messages to all
                    }
                }// end of while
             } // try
             catch(Exception e) 
             {
               System.out.println(e.getMessage());
             }
        }
    

    For Point 2 :

    Seems to me in this you are typing to the console to get the input, in that case atleast for once you have to type what you have to send to the other side, then you can add your modification to this as shown in the first line of the method, broadcast();, so that you can satisfy your need for Point 2, or (else You can let the server side send it back to the client, the message which containts the name, it will be like a client send his message to the server and the server is sending all the clients back.)

    public void boradcast(String user, String message)  
    {
        System.out.println(user + " : " + message);
        // send message to all connected users
        for (HandleClient c : clients)
        if (!c.getUserName().equals(user))
        {
            c.sendMessage(user,message);
        }
    }
    

    And for Point 3, you can write your conversation to the file or save it to the database, which ever way is appropriate to you.

    And since you said you are new to Java, you better look at java.nio. This package is better than the previous java.io package.

    LATEST EDIT :

    Try this small sample code, hope this might do what you asking for :

    import java.io.*;
    
    public class StringConsole
    {
        public static void main(String... args) throws IOException
        {
            int count = 0;
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            while (count < 5)
            {
                System.out.print("My Name : ");
                String message = br.readLine();
                count++;
            }   
        }
    }
    

    Hope this might help you in some way.

    Regards

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to make a simple chat server in Java. Now I have a
im making a simple TCP client-server in c and im trying to send a
I'm making server that make a tcp socket and work over port range, with
I'm making an application server client using tcp sockets in c# .. The application
i have a tcp server that, when a client connects, it makes a new
This is similar to my last question. I'm making a simple tcp/ip chat program
I'm making a client-server program for picking a file from a location on a
I'm making a TCP Client in Applet mode and I get this strange error...
We have a .NET application which, on a certain server, keeps making various TCP
The code below aims at making TCP Server and Clients. But when the number

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.