我正在使用Android应用程序通过TCP套接字与同一LAN上的PC java应用程序进行通信,发送和接收消息。下面是我在Android中使用的Asynctask代码发送消息并从PC接收回复:
public class Client extends AsyncTask<Void, Void, Void> {
Context context;
String dstAddress;
int dstPort;
String msg;
Client(Context context, String addr, int port, String msg) {
this.context = context;
dstAddress = addr;
dstPort = port;
this.msg = msg;
}
String reply = "";
@Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
BufferedWriter dout = new BufferedWriter( new OutputStreamWriter( socket.getOutputStream() ));
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//send request
dout.write(msg);
dout.flush();
dout.close();
//get response
reply = br.readLine();
br.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// DISPLAY REPLY CONTENT
Handler handler = new Handler(context.getMainLooper());
handler.post( new Runnable(){
public void run(){
Toast.makeText(context, "Server reply: " + reply ,Toast.LENGTH_LONG).show();
}
});
}
}
下面是处理客户端套接字的服务器线程,该线程基本上在serversocket接受套接字时运行:
static class clientThread extends Thread {
Socket s = null;
clientThread(Socket s) //constructor
{
this.s = s;
}
@Override
public void run ()
{
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); //receiving data into a buffered reader
String dataIn = br.readLine(); // reading the buffered data into a string
System.out.println("received: " + dataIn);
//BufferedWriter dout = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//dout.write("OK");
//dout.newLine();
PrintWriter dout = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())), true);
if(dataIn.equals("Android client"))
{
dout.println("OK");
dout.flush();
System.out.println("OK sent");
}
dout.close();
br.close();
s.close();
}
catch (IOException e)
{ System.out.println("Error occured"); }
}
}
所以总结程序,android发送消息“Android客户端”(服务器收到并在控制台上打印没有问题),现在回复,服务器发送“OK”也没有问题但是android方面什么也没收到。 如前所述,如果我删除 dout.close(); 在我发送消息后,从android的asynctask,服务器只在程序终止时收到消息,我不明白为什么我必须关闭它才能成功发送消息。
答案 0 :(得分:0)
您正在阅读线路,但您没有发送线路。在客户端发送的消息中添加行终止符,或使用BufferedWriter.newLine()
;和flush()
而不是关闭缓冲的作家。