如何让服务器从客户端接收多个消息?

How to let a server receive more than a single message from clients?

我想要一个 运行ning 的服务器并接收来自客户端(例如另一个 Java 应用程序)的消息。我正在通过带有 InputStream 的 BufferedReader 执行此操作,只要我执行一次,它就会按预期工作。该消息由该方法处理并在屏幕上写入接收到的消息的测试消息,但如果我让它 运行 在 while 循环中它说 -

java.net.SocketException: Connection reset

所以一旦服务器收到一条消息,我就不知道如何获得第二条或任何后续消息。

我的主要源代码是:

public static void main (String[] args)  {

    int port = 13337;
    BufferedReader msgFromClient = null;
    PrintWriter msgToClient = null;

    timeDate td = new timeDate(); //Class i did for myself to get time/date

    ServerSocket s_socket = null;
    try {
        s_socket = new ServerSocket(port);
        System.out.println("Server startet at "+td.getCurrDate()+" "+td.getCurrTime());
    }
    catch (IOException ioe) {
        System.out.println("Server on Port "+port+" couldnt be created. \nException: "+ioe.getMessage());
    }

    Socket socket = null;
    try {
        socket = s_socket.accept();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        msgFromClient = utils.createInputStream(socket);
    } catch (IOException ioe) {
        System.out.println("Creation of an Input Stream failed.\n Exception - "+ioe);
    }
    try {
        msgToClient   = utils.createOutputStream(socket);
    } catch (IOException ioe) {
        System.out.println("Creation of an Output Stream failed.\n Exception - "+ioe);
    } 

    String input = null;
    while (true) {
            try {
                input = msgFromClient.readLine();
            } catch (IOException ioe) {
                System.out.println(ioe);
            }
            if(input!=null) {
                System.out.println("Jumping out of loop: "+input);
                utils.processCode(input);
            }
    } 

创建流的两个 class 看起来像这样:

public static BufferedReader createInputStream (Socket socket) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    return br;
}

public static PrintWriter createOutputStream (Socket socket) throws IOException {

    PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);

    return pw;
}   

然后"processCode"class简直就是一个开关。

Socket socket = null;
try {
    socket = s_socket.accept();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

您只接受一个连接,此后您将进行处理。您需要为每个连接打开一个新线程

ExecutorService threadLimit = Executors.newFixedThreadPool(10);
    while(true)  {
        Socket s = serverSocket.accept();
        treadLimit.submit(new HandleThread(s));
    }