Java线程:如何关闭套接字而不会出现错误(客户端/服务器通信)

时间:2017-04-20 01:45:12

标签: java multithreading sockets

编辑:刷新,我在最后添加了一个问题

该程序的目的是能够在多个客户端和一个服务器之间发送/接收消息(解码/编码的utf-8字符串)。

连接客户端后,它会从标准输入向服务器发送消息。

然后,服务器将收到的消息发送给所有其他客户端(不包括发送消息的客户端)。

有两个程序文件(一个客户端文件一个服务器文件)。

每个文件都有一个帖子。

当程序运行时,只有一个服务器,可以有多个和/或无限数量的客户端。

创建客户端的方法是打开一个新的命令提示符/ mac终端窗口并运行客户端文件(这可以无限次地完成)。

创建服务器的方法是打开一个新的命令提示符/ mac终端窗口并运行服务器文件(这只能执行一次)。

必须为连接到服务器的每个客户端创建一个新线程。

错误的屏幕截图(显示的是84行):

enter image description here

ChatClient的第33行的屏幕截图

enter image description here

客户代码:

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

服务器代码:

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

我的问题是:我该如何摆脱错误?出于某种原因,它似乎涉及客户端和服务器文件(客户端中的第33行和服务器中的84)

0 个答案:

没有答案