我在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();
}
Android服务器代码
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();
}
}
答案 0 :(得分:1)
问题是以下代码部分:
while(readerIn.readLine()!=null){
final String incomingMsg = readerIn.readLine();
....
在第一行中,您正在阅读该行并忽略它。因此,你每隔一秒就丢掉一次。
读取和使用while循环的正确方法是:
String incomingMsg;
while((incomingMsg = readerIn.readLine())!=null){
....
}