java tcp发消息给硬件_java – TCP客户端/服务器通信只发送第一条消息?
我在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");
}
}
}
客戶:
客戶端是一個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/20190826/1734001.html
總結
以上是生活随笔為你收集整理的java tcp发消息给硬件_java – TCP客户端/服务器通信只发送第一条消息?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言和java和汇编语言_C语言和汇编
- 下一篇: 网页上点击java没反应_JavaScr