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

  • Home
  • SEARCH
  • 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 417661
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T18:36:08+00:00 2026-05-12T18:36:08+00:00

FYI This is homework. I have to build a Java Chat server. I have

  • 0

FYI This is homework. I have to build a Java Chat server. I have been able to build a server which communicates with 1 client. But I need this to communicate with multiple users.

A user is supposed to type in the person’s name they wish to talk to followed by a dash (-) and then the message to be sent. I am able to get users signed on but I am not able to get the list of users to print out or the messages to send to other users. Here is the server code:

/** 
    Threaded Server
*/

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Set;

public class ThreadedServer
{
    public static void main( String[] args) throws Exception
    {
        HashMap<String, Socket> users = new HashMap<String, Socket>( );
        ServerSocket server = new ServerSocket(5679);
        System.out.println( "THE CHAT SERVER HAS STARTED! =)" );
        while(true)
        {
            Socket client = server.accept();
            ThreadedServer ser = new ThreadedServer();
            ClientFromThread cft =ser.new ClientFromThread(client);
            String name = cft.getUserName();
            users.put( name, client );
            cft.giveUsersMap( users );
            //cft.giveOnlineUsers( ); //DOES NOT WORK YET!!!!
            System.out.println("Threaded server connected to " 
                        + client.getInetAddress() + "  USER: " + name );            
        } 

    }

    //***************************************************************************************************

    class ClientFromThread extends Thread
    {
        private Socket client;
        private Scanner fromClient;
        private PrintWriter toClient;
        private String userName;
        HashMap<String, Socket> users;

        public ClientFromThread( Socket c ) throws Exception
        {
            client = c;
            fromClient = new Scanner( client.getInputStream() );
            toClient = new PrintWriter( client.getOutputStream(), true );
            userName = getUser();
            start();
        }
        public void giveUsersMap( HashMap<String, Socket> users )
        {
            this.users = users;
        }

        //THIS DOESNT WORK YET... IT PRINTS THE FIRST LINE BUT NOT THE LIST
        public void giveOnlineUsers()
        {
            toClient.println("These users are currently online:");
            Set<String> userList = users.keySet();
            String[] userNames = null;
            userList.toArray( userNames );

            for( int i = 0; i< userNames.length; i++ )
            {
                toClient.println(userNames[i]);
            }
        }

        public String getUserName()
        {
            return userName;
        }

        private String getUser()
        {
            String s = "";
            while( (s.length() < 1) || (s == null) )
            {
                toClient.println("What is your first name? ");
                s=fromClient.nextLine().trim();
            }
            toClient.println("Thank You! Welcome to the chat room " + s + ".");
            return s.toUpperCase();
        }

        public void run() 
        {
            String s = null;
            String toUser;
            String mesg;

            while( (s=fromClient.nextLine().trim()) != null )
            {
                if( s.equalsIgnoreCase( "END" )) break;

                for( int i=0; i<s.length(); i++)
                {
                    if( s.charAt(i) == '-' )
                    {
                        toUser = s.substring( 0, i ).trim().toUpperCase();
                        mesg = s.substring( i+1 ).trim();
                        Socket client = users.get( toUser );
                        try
                        {
                            ClientToThread ctt = new ClientToThread(client);
                            ctt.sendMesg( mesg, toUser );
                            ctt.start();
                        }
                        catch(Exception e){e.printStackTrace();}
                        break;
                    }
                    if( (i+1) == s.length() )
                    {
                        toClient.println("Sorry the text was invalid. Please enter a user name " +
                                                     "followed by a dash (-) then your message.");
                    }
                }
            }
            try
            {
                fromClient.close();
                toClient.close();
                client.close();
            }
            catch(Exception e){e.printStackTrace();}
        }

    } //end class ClientFromThread

    //***************************************************************************************************

    class ClientToThread extends Thread
    {
        private Socket client;
        private PrintWriter toClient;
        private String mesg;

        public ClientToThread( Socket c ) throws Exception
        {
            client = c;
            toClient = new PrintWriter( client.getOutputStream(), true );
        }

        public void sendMesg( String mesg, String userName )
        {
            this.mesg = userName + ": " + mesg;
        }
        public void run() 
        {
            toClient.println(mesg);

            try
            {
                toClient.close();
                client.close();
            }
            catch(Exception e){e.printStackTrace();}
        }

    } //end class ClientToThread

    //***************************************************************************************************

} //end class ThreadedServer

Here is the Client code”

import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;


public class ReverseClient 
{
public static void main( String[] args ) throws Exception
{
    String line = null;
    Socket server= new Socket( "10.0.2.103", 5679);
    System.out.println( "Connected to host: " + server.getInetAddress() );
    BufferedReader fromServer = new BufferedReader(
                new InputStreamReader(server.getInputStream()) );
    PrintWriter toServer = new PrintWriter( server.getOutputStream(), true );
    BufferedReader input = new BufferedReader( 
                new InputStreamReader(System.in) );
    while( (line=input.readLine()) !=null )
    {
        toServer.println(line);
        System.out.println( fromServer.readLine() );
    }
    fromServer.close();
    toServer.close();
    input.close();
    server.close();

}   
}

Here is the console output (the top is the server, bottom is the client):
alt text

I am getting errors (as shown in the image above) and the messages are not sending. Any suggestions on how to take care of these issues?

  • 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-12T18:36:08+00:00Added an answer on May 12, 2026 at 6:36 pm

    So far I found this to be a problem, but I don’t think this is the only problem..

    This will help the NoSuchElementException
    On around line 90 Change this…

    while( (s=fromClient.nextLine().trim()) != null )
    {
    

    to this…

    while(fromClient.hasNext())
    {
       s = fromClient.nextLine().trim();
    

    OK just found another problem in ClientToThread.run()… You are closing the client connections after you send the first message. I commented them both out and it seems to be working a little better.

    public void run()
      {
         toClient.println(mesg);
         try {
            //toClient.close();
            //client.close();
         }
         catch (Exception e)  {
            e.printStackTrace();
         }
      }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 228k
  • Answers 229k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The C++ standard says nothing about a heap, nor about… May 13, 2026 at 1:42 am
  • Editorial Team
    Editorial Team added an answer I think you'll have to give strtotime some other (and/or… May 13, 2026 at 1:42 am
  • Editorial Team
    Editorial Team added an answer When you decalre a reference type as readonly, only the… May 13, 2026 at 1:42 am

Related Questions

What would be a clever way to make a 'please wait' control for a
How do you find the smallest unused number in a SQL Server column? I
Kind of similar to how the Related Questions search works here when posting questions:
My website has a SSL certificate for www.reallygreattoys.com. If you try to go to

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.