如何让我的TCP服务器不断接收数据?

时间:2015-03-02 11:46:28

标签: java tcp

我知道,这是一个愚蠢的新手问题。但是,在互联网上,只有可怕的TCP服务器示例。像这样:

try {
    Socket skt = new Socket("localhost", 1332);
    BufferedReader in = new BufferedReader(new
    InputStreamReader(skt.getInputStream()));
    System.out.print("Received string: '");

    while (!in.ready()) {}
    System.out.println(in.readLine()); // Read one line and output it
    System.out.print("'\n");
    in.close();
} catch(Exception e) {
    System.out.print("Whoops! It didn't work!\n");
}

我如何处理多个客户端,并且能够不断接收数据而不仅仅关闭输入流?

互联网上没有容易找到的代码片段。

1 个答案:

答案 0 :(得分:1)

您展示的代码适用于客户端,这是一个与服务器通信以进行特定会话的应用程序。

对于服务器(如here),您可以使用ServerSocket输入特定的端口号。套接字侦听端口,每次有人要连接时都会创建连接。该连接是服务器与客户端通信的某种会话。

服务器的最小例子就是:

class TCPServer {

   public static void main(String argv[]) throws Exception {
         int port = 8081;
         ServerSocket waiting = new ServerSocket(port);

         while(true) {
            Socket socket = waiting.accept(); //wait until a client shows up
            new SessionHandler(socket).start();//create new handler with the socket
            //start listening again
         }
      }
}

所以你在.accept循环中运行while,这样从你收到客户端连接的那一刻起,你就等了另一个。

SessionHandler

一样
class SessionHandler extends Thread {

    private Socket socket;

    public SessionHandler (Socket socket) {
        this.socket = socket;
    }

    public void run () {
        //handle the session using the socket (example)
        BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
        DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
        //read input from inFromClient, write to outToClient
    }

}

现在在工业TCP服务器上,故事的结果有点复杂:您将使用线程池来防止服务器过多工作等。