我正在尝试编写Java服务器,以便Android客户端可以向其发送字符串,服务器将使用自己的字符串进行回复。第一部分工作,客户端向服务器发送字符串,但服务器发送消息不起作用:数据包使其脱离服务器,但Android客户端不接收它。有没有人有关于如何解决这个问题的建议?
此整个过程以前在Python服务器上运行,但由于库支持(Java更好地支持NAT遍历),我将更改为Java
服务器(Java):
public class TCPServer implements Runnable {
private Thread t = null;
@Override
public void run() {
// TODO Auto-generated method stub
String receive;
String response = "1||2||3||4\n";
ServerSocket tcpServer = null;
Socket tcpClient = null;
try {
tcpServer = new ServerSocket(4999);
System.out.println(" TCP open for connections");
while(true) {
tcpClient = tcpServer.accept();
BufferedReader inStream = new BufferedReader(new InputStreamReader(tcpClient.getInputStream()));
receive = inStream.readLine();
System.out.println("Server <<< " + receive);
DataOutputStream outStream = new DataOutputStream(tcpClient.getOutputStream());
outStream.write(response.getBytes("UTF-8"));
outStream.flush();
System.out.println("Server >>> " + response);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("IOException: " + e.toString());
} finally {
if (tcpServer != null) {
try {
tcpServer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("IOException: " + e.toString());
}
}
if (tcpClient != null) {
try {
tcpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("IOException: " + e.toString());
}
}
}
}
public void start() {
// TODO Auto-generated method stub
if(t == null) {
t = new Thread(this);
t.start();
System.out.println("Start TCP Server");
}
}
}
客户端(Android):
public class AsyncTCPSend extends AsyncTask<Void, Void, Void> {
String address = "";
String message = "";
String response = "";
AsyncTCPSend(String addr, String mes) {
address = addr;
message = mes + "\n";
}
@Override
protected Void doInBackground(Void... params) {
Socket socket = null;
try {
socket = new Socket(address, 4999);
socket.getOutputStream().write(message.getBytes());
ByteArrayOutputStream writeBuffer = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream writeIn = socket.getInputStream();
while((bytesRead = writeIn.read(buffer)) != -1) {
writeBuffer.write(buffer,0,bytesRead);
response += writeBuffer.toString("UTF-8");
}
} catch (UnknownHostException e){
e.printStackTrace();
response = "Unknown HostException: " + e.toString();
System.out.println(response);
} catch (IOException e) {
response = "IOException: " + e.toString();
System.out.println(response);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
recieve.setText(response);
super.onPostExecute(result);
}
}
答案 0 :(得分:0)
我不知道为什么要调用InputStream&#39; writeIn&#39;,但问题是客户端正在读取套接字直到流结束,并且服务器永远不会关闭接受的套接字,所以流的结束永远不会发生。