【问题标题】:MultiThreaded Socket Server Java, connection reset SocketException多线程套接字服务器 Java,连接重置 SocketException
【发布时间】:2014-05-07 12:48:29
【问题描述】:

这是我的服务器类代码。

无效运行()

    try{
        //1. creating a server socket
        providerSocket = new ServerSocket(2004, 10);
        //2. Wait for connection
        System.out.println("Waiting for connection");
        connection = providerSocket.accept();
        //connections++;
        System.out.println("Connection received from " + connection.getInetAddress().getHostName());
        //3. get Input and Output streams
        out = new ObjectOutputStream(connection.getOutputStream());
        out.flush();
        in = new ObjectInputStream(connection.getInputStream());
        message = new Message();
        //sendMessage(message);
        //4. The two parts communicate via the input and output streams
        do{
            try{
                message = (Message)in.readObject();
                System.out.println("client>" + message.status);
                System.out.println(message.status);
                Protocol pro = new Protocol();
                message.setProtocol(pro);
                sendMessage(message);

                message.connect = false;
            }
            catch(ClassNotFoundException classnot){
                System.err.println("Data received in unknown format");
            }
        }while(message.connect);
    }
    catch(IOException ioException){
        ioException.printStackTrace();
    }
    finally{
        //4: Closing connection
        try{
            in.close();
            out.close();
            providerSocket.close();
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
    } 
}
void sendMessage(Message msg)
{
    try{

        out.writeObject(msg);
        out.flush();
        System.out.println("server>" + msg.status);
    }
    catch(IOException ioException){
        ioException.printStackTrace();
    }

}

然后是我的客户端类:

public void run()
{
    try{
        //1. creating a socket to connect to the server
        requestSocket = new Socket(InetAddress.getLocalHost(), 2004);
        message = new Message();
        System.out.println("Connected to localhost in port 2004");
        //2. get Input and Output streams
        out = new ObjectOutputStream(requestSocket.getOutputStream());
        out.flush();
        in = new ObjectInputStream(requestSocket.getInputStream());
        //3: Communicating with the server
        do{
            try{

                message.status = "connected";

                message.actionUser.setUserID(1);
                message.actionUser.setPassword("bear");
                sendMessage(message);

                message = (Message)in.readObject();
                Object output = message.getProtocol().processInput(message);
                message.connect = false;
                message.status = "Disconnected";
                //sendMessage(message);
            }
            catch(Exception e){
                System.err.println("data received in unknown format");
                System.err.println(e.getMessage());
            }
        }while(message.connect);
    }
    catch(UnknownHostException unknownHost){
        System.err.println("You are trying to connect to an unknown host!");
    }
    catch(IOException ioException){
        ioException.printStackTrace();
    }
     finally{
        //4: Closing connection

            try{
                if(requestSocket.isInputShutdown())
                in.close();
                if(requestSocket.isOutputShutdown())
                out.close();
                requestSocket.close();
            }
            catch(IOException ioException){
                ioException.printStackTrace();
            }
         }

}

当我尝试多线程运行它们时出现这些错误。它一次工作一个,但在两个客户端线程运行时不起作用。 sendMessage 只是 writeObject(msg),其中 msg 是我要发送的 Message 对象。

来自客户端类的错误消息

Connected to localhost in port 2004
Connected to localhost in port 2004
client>connected
java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.io.ObjectInputStream$PeekInputStream.read(Unknown Source)
    at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
    at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
    at java.io.ObjectInputStream.<init>(Unknown Source)
    at auction.Requester.run(Requester.java:22)
    at java.lang.Thread.run(Unknown Source)

在第一个线程在服务器上成功运行后出现: 从 152.78.175.6 收到的连接 客户端>已连接 连接的 服务器>已连接 用户 1 已登录 等待连接

它崩溃的那一行 (22) 是 out = new ObjectOutputStream(connection.getOutputStream());

任何帮助将不胜感激

【问题讨论】:

    标签: java multithreading sockets serversocket objectinputstream


    【解决方案1】:

    您的服务器套接字不是多线程的。您需要执行以下操作才能处理多个客户端:

    public class MultiThreadServer implements Runnable {
       Socket csocket;
       MultiThreadServer(Socket csocket) {
          this.csocket = csocket;
       }
    
       public static void main(String args[]) 
       throws Exception {
          ServerSocket ssock = new ServerSocket(1234);
          System.out.println("Listening");
          while (true) {
             Socket sock = ssock.accept();
             System.out.println("Connected");
             new Thread(new MultiThreadServer(sock)).start();
          }
       }
       public void run() {
          try {
             PrintStream pstream = new PrintStream
             (csocket.getOutputStream());
    
             // handle all input output here.
    
             pstream.close();
             csocket.close();
          }
          catch (IOException e) {
             System.out.println(e);
          }
       }
    }
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      让你的服务器多线程,这样它就可以在不同的线程中处理每个客户端。

      试试这个:

      Class ConnectionThread extends Thread {
      
      Socket connection;
      ObjectInputStream in;
      OjectOutputStream out;
      Message message;
      
      Connection Thread(Socket connection) {
          this.connection = connection;
      }
      
      void run() {
          try {
              System.out.println("Connection received from " + connection.getInetAddress().getHostName());
              out = new ObjectOutputStream(connection.getOutputStream());
              out.flush();
              in = new ObjectInputStream(connection.getInputStream());
              message = new Message();
      
              do{
                  try{
                      message = (Message)in.readObject();
                      System.out.println("client>" + message.status);
                      System.out.println(message.status);
                      Protocol pro = new Protocol();
                      message.setProtocol(pro);
                      sendMessage(message);
                      message.connect = false;
                  } catch(ClassNotFoundException classnot){
                      System.err.println("Data received in unknown format");
                  }
              } while(message.connect);
          }
          catch(IOException ioException){
              ioException.printStackTrace();
          }
          finally{
              try{
                  in.close();
                  out.close();
                  providerSocket.close();
              } catch(IOException ioException){
                  ioException.printStackTrace();
              }
          }
      }
      void sendMessage(Message msg) {
          try{
              out.writeObject(msg);
              out.flush();
              System.out.println("server>" + msg.status);
          } catch(IOException ioException){
              ioException.printStackTrace();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-02
        • 1970-01-01
        相关资源
        最近更新 更多