gpt4 book ai didi

java - TCP 客户端/服务器通信只发送第一条消息?

转载 作者:可可西里 更新时间:2023-11-01 02:33:34 25 4
gpt4 key购买 nike

我正在用 java 设置一个简单的 TCP 客户端服务器交互。

服务器:

服务器是用 Java 编写的桌面客户端:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

class TCPServer
{
public static int PORT_NUMBER = 6129;

public static void main(String argv[]) throws Exception
{
String clientMessage;
ServerSocket welcomeSocket = new ServerSocket(PORT_NUMBER);

while (true)
{
Socket connectionSocket = welcomeSocket.accept();

BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

clientMessage = inFromClient.readLine();

System.out.println("Received: " + clientMessage);

outToClient.writeBytes("I received this: "+ clientMessage +"\n");
}
}
}

客户:

客户端是一个通过 TCP 连接到服务器的 android 应用程序。在客户端中,我有一个方法 sendMessage(String msg) 尝试向服务器发送消息。

public static void sendMessage(String msg) throws IOException
{
if (mainSocket == null)
{
return;
}
if (!mainSocket.isConnected())
{
connectSocket();
}
PrintWriter output = new PrintWriter( mainSocket.getOutputStream());
output.println(msg);
output.flush();
System.out.println(msg);
}

问题是,服务器接收到第一条消息,但任何后续消息都不会显示。当我关闭客户端时,所有其他消息突然同时出现在服务器中。

这是服务器看到的:

Received: message 1

长时间没有 Activity ...
然后我关闭客户端

Received: message 2 message 3 message 4 message 5 etc..

我在 sendMessage() 方法中放置了一个 println,该方法本身是实时调用的。

最佳答案

每次发送消息时,您都需要在客户端显式close() 您的PrintWriter。当您完成读取 inFromClient 时,服务器端也是如此,当您完成写入 outToClient 时,同样如此。

另见 basic example , 他们很好地解释了基本的工作流程:

However, the basics are much the same as they are in this program:

Open a socket.

Open an input stream and output stream to the socket.

Read from and write to the stream according to the server's protocol.

Close the streams.

Close the socket.

关于java - TCP 客户端/服务器通信只发送第一条消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7154071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com