MultiThreaded Socket Server Java, connection reset SocketException

This is my code for my Server class.

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

}

Then my client class:

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

}

and I get these errors when I try run them MultiThreaded. It works one at a time but not when two Client threads run. The sendMessage is just writeObject(msg) where msg is a Message object i'm trying to send.

Error messages from Client class

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)

These appear after the first thread sucessfully runs on the Server: Connection received from 152.78.175.6 client>connected connected Server>connected User 1 has been logged in Waiting for connection

The line where it crashes (22) is out = new ObjectOutputStream(connection.getOutputStream());

Any help would be greatly appreciated


Your Server socket is not multi threaded. You need to do something like this in order to process multiple clients:

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

Hope this helps.


Make your server multithread so it can handle each client in different thread.

Try this:

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();
    }
}
链接地址: http://www.djcxy.com/p/35092.html

上一篇: Java:通过代码生成时,密钥库格式无效

下一篇: 多线程Socket服务器Java,连接重置SocketException