gpt4 book ai didi

java - TCP android 服务器没有收到来自 Java TCP 客户端的第一条消息

转载 作者:行者123 更新时间:2023-11-30 00:00:14 24 4
gpt4 key购买 nike

我在 java 中有一个 TCP 客户端,在 android 中有一个 TCP 服务器。将消息从服​​务器发送到客户端工作正常但是当消息从客户端发送到服务器(android)时它不显示消息但是当第二次重复相同的过程时,服务器显示消息即java客户端的发送按钮应该被按下两次然后只有消息显示在 android 应用程序中。

Java 客户端代码

//btn handelar to send message form textarea
private class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
String outputLine = txArea.getText ();
System.out.println ("Client > " + outputLine);
out.println (outputLine);
out.flush();


}
}

//receiving message
public void run () throws IOException
{
Socket socket = new Socket ("192.168.123.3",1234);
BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
out = new PrintWriter (socket.getOutputStream (), true);

String inputLine;

while ((inputLine = in.readLine ()) != null)
{
System.out.println ("Client < " + inputLine);
rxArea.setText (inputLine);
}


out.close();
in.close();
socket.close();
}

安卓服务器代码

 public void runTcpServer(){

handel = new Handler();
try {

int a = Integer.parseInt(new SettingDialog().port);
//creating a socket to listen on a given port
Log.i("NW LOG","PORT OPENED SUCESSFULLY in "+a);
final ServerSocket serverSocket = new ServerSocket(a);

Thread listenConnection = new Thread(new Runnable() {
@Override
public void run() {

try {

//accepting the incoming socket connection request
Socket workstationSocket = serverSocket.accept();
//reading the incoming content
BufferedReader readerIn = new BufferedReader(new InputStreamReader(workstationSocket.getInputStream()));

outMessage = new PrintStream(workstationSocket.getOutputStream(),true);


Log.i("NW LOG","WATING FOR MSG");
while(readerIn.readLine()!=null){

final String incomingMsg = readerIn.readLine();

//setting incoming message to UI thread using handler
handel.post(new Runnable() {
@Override
public void run() {
setMessage(IN,incomingMsg);
}
});


}
outMessage.close();
readerIn.close();
workstationSocket.close();
serverSocket.close();



} catch (IOException e) {
e.printStackTrace();
}


}
});listenConnection.start();

} catch (IOException e) {
e.printStackTrace();
}


}

最佳答案

问题出在以下代码部分:

while(readerIn.readLine()!=null){
final String incomingMsg = readerIn.readLine();
....

在第一行中,您正在阅读该行并忽略它。因此,您每隔一行就扔掉一次。

在 while 循环中阅读和使用它的正确方法是这样的:

String incomingMsg;
while((incomingMsg = readerIn.readLine())!=null){
....
}

关于java - TCP android 服务器没有收到来自 Java TCP 客户端的第一条消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50066145/

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