我正在使用 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的异步任务中,服务器仅在程序终止时接收消息,我不明白为什么我必须关闭它才能成功发送消息。
您正在阅读线路,但您没有发送线路。在客户端发送的消息中添加行终止符,或者使用BufferedWriter.newLine()
; 而flush()
不是关闭缓冲的写入器。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句