MultiThreaded套接字服务器Java,连接重置SocketException

时间:2014-05-07 12:48:29

标签: java multithreading sockets serversocket objectinputstream

这是我的服务器类的代码。

void run()

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

}

我尝试运行MultiThreaded时遇到这些错误。它一次运行一个,但不运行两个客户端线程。 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 客户机GT;连接 连接的 服务器&GT;连接 用户1已登录 等待连接

崩溃的行(22)out = new ObjectOutputStream(connection.getOutputStream());

非常感谢任何帮助

2 个答案:

答案 0 :(得分:0)

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

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

希望这有帮助。

答案 1 :(得分:0)

使您的服务器成为多线程,以便它可以处理不同线程中的每个客户端。

试试这个:

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