0

EDIT: refresh, I added a question at the end

The purpose of this program is to be able to send/recieve messages (decoded/encoded utf-8 strings) between multiple clients and one server.

Once a client is connected, it sends messages to the server from standard input.

The server then sends the received message to all other clients (not including the client that sent the message).

There are two program files (one client file one server file).

Each file has one thread.

When the program is run, there is only one server, there can be a multiple and/or infinite number of clients.

The way to create a client will be opening a new command prompt / mac terminal window and run the client file (this can be done an infinite number of times).

The way to create the server will be opening a new command prompt / mac terminal window and run the server file (this can only be done once).

One new thread has to be created for each client that connects to the server.

Screenshot of error (line at 84 shown):

enter image description here

Screenshot of line 33 at ChatClient

enter image description here

Code of client:

import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatClient
{
    private static Socket Socket;
    static int numberOfClients = 0;
    public static void main(String args[]) 
    {
              //If I wanted to create multiple clients, would this code go here? OR should the new thread creation be outside the while(true) loop?
              while (true)
              {
                  String host = "localhost";
                  int numberOfClients = 0;
                  Thread ChatClient1 = new Thread ()
                  {
                      public void run()
                      {   
                          try
                          {
                              //Client begins, gets port number, listens, connects, prints out messages from other clients

                              int numberofmessages = 0;
                              String[] messagessentbyotherclients = null;
                              System.out.println("Try block begins..");
                              System.out.println("Chat client is running");
                              String port_number1= args[0];
                              System.out.println("Port number is: " + port_number1);
                              int port = Integer.valueOf(port_number1);
                              System.out.println("Listening for connections..");
                              System.out.println( "Listening on port: " + port_number1 );
                              Socket.connect(null);
                              System.out.println("Client has connected to the server");
                              for(int i = 0; i < numberOfClients; i++)
                              {
                                  System.out.println(messagessentbyotherclients);
                              }

                              //client creates new message from standard input
                              OutputStream os = Socket.getOutputStream();
                              OutputStreamWriter osw = new OutputStreamWriter(os);
                              BufferedWriter bw = new BufferedWriter(osw);

                              //creating message to send from standard input
                              String newmessage = "";
                              try   
                              {
                                  // input the message from standard input encoded in UTF-8 string format
                                  BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
                                  String line = "";
                                  System.out.println( "Standard input (press enter then control D when finished): " );
                                  while( (line= input.readLine()) != null )     
                                  {
                                      newmessage += line + " ";
                                      input=null;
                                  }
                              }
                              catch ( Exception e )
                              {
                                  System.out.println( e.getMessage() );
                              }
                              //Sending the message to server
                              String sendMessage = newmessage;
                              bw.write(sendMessage + "\n");
                              bw.flush();
                              System.out.println("Message sent to server: "+sendMessage);
                          } 
                          catch (IOException e)
                          {
                            e.printStackTrace();
                          }
                      }
                  };
                  ChatClient1.start();
        }
    }
}

Code of server:

import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatServer
{
    private static Socket socket;

    public static void main(String args[])
    {
        Thread ChatServer1 = new Thread () 
        {
            public void run ()
            {   
                System.out.println("Server thread is now running");
                try
                {

                    int numberOfClients = 0;
                    boolean KeepRunning = true;
                    int port_number1= Integer.valueOf(args[0]);
                    System.out.println("Waiting for connections on port " + port_number1);
                    ServerSocket serverSocket = new ServerSocket(port_number1);
                    try 
                    {
                        serverSocket = new ServerSocket(port_number1);
                    } 
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                    System.out.println( "Listening for connections on port: " + ( port_number1 ) );
                    while(KeepRunning)
                    {
                        //create a list of clients
                        ArrayList<String> ListOfClients = new ArrayList<String>();

                        //connect to client
                        socket = serverSocket.accept();  

                        //add new client to the list, is this the right way to add a new client? or should it be in a for loop or something?
                        ListOfClients.add("new client");
                        numberOfClients += 1;

                        System.out.println("A client has connected. Waiting for message...");
                        ListOfClients.add("new client" + numberOfClients);

                        //reading encoded utf-8 message from client, decoding from utf-8 format 
                        String MessageFromClientEncodedUTF8 = "";
                        BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));  
                        String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
                        byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8"); 
                        String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");


                        //relaying message to every other client besides the one it was from

                        for (int i = 0; i < ListOfClients.size(); i++)
                        {
                            if(ListOfClients.get(i)!="new client")
                            {
                                   String newmessage = null;
                                   String returnMessage = newmessage;
                                   OutputStream os = socket.getOutputStream();
                                   OutputStreamWriter osw = new OutputStreamWriter(os);
                                   BufferedWriter bw = new BufferedWriter(osw);
                                   bw.write(returnMessage + "\n");
                                   System.out.println("Message sent to client: "+returnMessage);
                                   bw.flush();
                            }
                        }

                    }
                } 
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
                finally
                {
                    try 
                    {
                        socket.close();
                    } 
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }

            }
        };
        ChatServer1.start();
    }
}

My question is: How should I go about getting rid of the error? For some reason it seems to involve both the client and the server files (line 33 in the client and 84 in the server)

0 Answers0