Java线程客户端空指针异常:我是否需要使用socket.connect()或socket.connect(null)才能将客户端连接到服务器?

时间:2017-04-21 16:40:18

标签: java multithreading sockets

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

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

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

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

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

我用来连接的端口号是5344(localhost)。

客户端错误的屏幕截图:

enter image description here

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

enter image description here

错误消息是:

Exception in thread “Thread-75562” java.lang.NullPointerException at ChatClient$1.run(ChatClient.java:39)

“39”是错误指向的代码行(我认为)。

ChatClient.java中第39行的屏幕截图:

enter image description here

我注意到有些人使用

Socket socket = new Socket(host, portNumber);

不调用任何Socket.connect(host,portNumber);连接到服务器。 是否需要使用socket.connect()将客户端连接到服务器?

ChatClient.java代码:

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 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 );
                              try 
                              {
                                  Socket.connect(null);
                              }
                              catch (IOException e1) 
                              {

                                e1.printStackTrace();
                              }
                              System.out.println("Client has connected to the server");
                              boolean KeepRunning = true;
                              while(KeepRunning)
                              {
                                  for(int i = 0; i < numberOfClients; i++)
                                  {
                                      System.out.println(messagessentbyotherclients);
                                  }
                                  try 
                                  {
                                    //client creates new message from standard input
                                    OutputStream os = Socket.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 
                                  {
                                    OutputStream os = Socket.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();    
              }
    }
}

ChatServer.java代码:

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 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();
    }
}

我的问题是:如何解决错误和/或我应该删除socket.connect(),同时还能以客户端身份连接到服务器?

0 个答案:

没有答案