TCP服务器只接收一条消息

时间:2015-08-19 08:38:13

标签: java sockets tcp

我正在尝试创建一个简单的TCP服务器和客户端。我希望客户端能够通过只打开一次套接字来发送多条消息。我查看了类似的问题hereherehere,但它们没有太多用处。

我的代码如下:

SampleServerTCP.java

public class SampleServerTCP {
    private static final int DEFAULT_PORT_NUMBER = 39277;

    public static void main(String[] args) throws IOException {
        ServerSocket defaultSocket = new ServerSocket(DEFAULT_PORT_NUMBER);

        System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
        while (true){
            Socket connectionSocket = defaultSocket.accept();
            BufferedReader fromClient= new BufferedReader(new     InputStreamReader(connectionSocket.getInputStream()));
            String msg = fromClient.readLine();
            System.out.println("Recieved: " + msg);
        }
    }
}

TCPClientTest.java

public class TCPClientTest {

    public static void main(String args[]) throws UnknownHostException, IOException, InterruptedException{
        Socket clientSocket = new Socket("localhost", 39277); 
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

        int c = 0;
        while(c<10){
            outToServer.writeBytes(c + "\n");
            outToServer.flush();
            c++;
            Thread.sleep(500);
        }
        clientSocket.close();
    }
}

我得到的唯一输出是:

Listening on port: 39277
Recieved: 0

我哪里错了?

2 个答案:

答案 0 :(得分:2)

你的问题在于:

ServerSocket defaultSocket = new ServerSocket(DEFAULT_PORT_NUMBER);

    System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
    while (true){
        Socket connectionSocket = defaultSocket.accept();
        BufferedReader fromClient= new BufferedReader(new     InputStreamReader(connectionSocket.getInputStream()));
        String msg = fromClient.readLine();
        System.out.println("Recieved: " + msg);
    }

您正在打开套接字,只读取一行,然后等待下一个套接字。

相反,你应该在循环之外Socket connectionSocket = defaultSocket.accept();,并在循环中读取此套接字,如下所示:

System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
Socket connectionSocket = defaultSocket.accept();
BufferedReader fromClient= new BufferedReader(new     InputStreamReader(connectionSocket.getInputStream()));
String msg = "";
while ((msg = fromClient.readLine()) != null){    
    System.out.println("Recieved: " + msg);
}

答案 1 :(得分:1)

更改服务器端代码,如下所示

公共类SampleServerTCP {     private static final int DEFAULT_PORT_NUMBER = 39277;

public static void main(String[] args) throws IOException {
    ServerSocket defaultSocket = new ServerSocket(DEFAULT_PORT_NUMBER);

    System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
     Socket connectionSocket = defaultSocket.accept();
     BufferedReader fromClient= new BufferedReader(new     InputStreamReader(connectionSocket.getInputStream()));
     String msg = fromClient.readLine();;
    while (msg!=null){



        System.out.println("Received: " + msg);
        msg = fromClient.readLine();
    }
}

}