Java Threads错误:线程错误中的异常加上数组索引超出范围异常加上Socket Exception / Connection Exception

时间:2017-04-21 23:53:54

标签: java multithreading sockets

我正在创建两个程序文件(一个客户端一个服务器)。

每个文件都有一个线程(一个用于服务器的线程,一个用于客户端的线程)

在运行时,应该只有一个服务器,并且应该有多个和/或可能无限数量的客户端同时连接到服务器)

为了让多个客户端运行,用户打开多个命令提示符/ mac终端窗口(每个窗口是一个客户端)(一个窗口是服务器,因此它至少需要运行两个窗口)

连接客户端后,它可以向服务器发送消息(utf-8字符串)。它还将从服务器接收从其他连接的客户端发送的所有消息(它不会接收从自身发送的消息)。

线程/数组索引超出范围错误(eclipse)中的异常屏幕截图:

enter image description here

Socket Exception错误(服务器)的屏幕截图:

enter image description here

客户端错误的屏幕截图:

enter image description here

服务器代码(ChatServer.java):

import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatServer
{
    ChatServer chatserver = new 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 port_number1 = 0;
                    int numberOfClients = 0;
                    boolean KeepRunning = true;
                    if(args.length>0)
                    {
                        port_number1 = Integer.valueOf(args[0]);
                    }
                    System.out.println("Waiting for connections on port " + port_number1);

                    try 
                    {
                         ServerSocket serverSocket = new ServerSocket(port_number1);
                         socket = serverSocket.accept();
                    } 
                    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 
                    {
                        if (socket != null)
                        {
                            socket.close ();
                        }

                    } 
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }

            }
        };
        ChatServer1.start();
    }
}

ChatClient.java代码:

import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatClient
{


    static int numberOfClients = 0;
    public static void main(String args[]) 
    {
      ChatClient chatclient = new ChatClient();

              //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 port = 0;
                              int port_1number1 = 0;
                              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);
                              if(args.length>0)
                              {
                                  port = Integer.valueOf(port_number1);
                              }
                              System.out.println("Listening for connections..");
                              System.out.println( "Listening on port: " + port_number1 );
                              boolean KeepRunning = true;
                              while(KeepRunning)
                              {
                                  for(int i = 0; i < numberOfClients; i++)
                                  {
                                      System.out.println(messagessentbyotherclients);
                                  }
                                  try 
                                  {
                                      Socket clientSocket = new Socket("localhost", port);
                                      InetAddress inetlocalhost = InetAddress.getByName("localhost");
                                      SocketAddress localhost = new InetSocketAddress(inetlocalhost, port);
                                      clientSocket.connect(localhost, port);
                                      System.out.println("Client has connected");
                                      //client creates new message from standard input
                                      OutputStream os = clientSocket.getOutputStream();
                                      OutputStreamWriter osw = new OutputStreamWriter(os);
                                      BufferedWriter bw = new BufferedWriter(osw);
                                  }
                                  catch (IOException e)
                                  {
                                    e.printStackTrace();
                                  }
                                  //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;
                                  try 
                                  {
                                    Socket clientSocket = new Socket("localhost", port);
                                    SocketAddress localhost = null;
                                    clientSocket.connect(localhost, port);
                                    OutputStream os = clientSocket.getOutputStream();
                                    OutputStreamWriter osw = new OutputStreamWriter(os);
                                    BufferedWriter bw = new BufferedWriter(osw);
                                    bw.write(sendMessage + "\n");
                                    bw.flush();
                                  } 
                                  catch (IOException e)
                                  {
                                    e.printStackTrace();
                                  }
                                  System.out.println("Message sent to server: "+sendMessage);
                              }

                          }
                          finally
                          {

                          }

                      }
                  };
                  ChatClient1.start();    
              }
    }
}

我的问题是:我应该如何解决所有三个错误(似乎我改变了代码的一部分,然后其他错误将仍然存在或因此而被解决,但我可能是错的)?我还想知道是否有办法在服务器代码中列出arraylist中的客户端数量,这样当客户端关闭他们的窗口时,我可以通过从列表中删除它来保持服务器。

0 个答案:

没有答案