我在java中设置一个简单的TCP客户端服务器交互.
服务器:
服务器是用Java编写的桌面客户端:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import .ServerSocket;
import .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");
}
}
}
客户:
客户端是一个Android应用程序,通过TCP连接到服务器.在客户端我有一个方法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
很长一段时间都没有活动……
然后我关闭了客户端
Received: message 2 message 3 message 4 message 5 etc..
我在sendMessage()方法中放了一个println,并且实时调用了方法本身.
解决方法:
每次发送消息时,您都需要在客户端显式关闭()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.
标签:android,java,tcp
来源: https://codeday.me/bug/0826/1734001.html