我目前正在学习在Java中使用套接字,但无法在套接字之间发送数据,在这种情况下,在android和计算机之间,如果这是相关的。我使用的方法是从这里。
请原谅糟糕的代码格式。
客户端:
PrintWriter out = null;
try {
Socket socket = new Socket("IP_OF_SERVER", 8000);
out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((fromServer = in.readLine()) != null) {
response = fromServer;
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
out.close();
}
...
textResponse.setText(response);
服务器端:
Socket hostThreadSocket = serverSocket.accept();
...
PrintWriter out = null;
String response,inputLine,outputLine;
try {
out = new PrintWriter(hostThreadSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(hostThreadSocket.getInputStream()));
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
outputLine = "Hello";
out.println(outputLine);
}
} catch (IOException ex) {
Logger.getLogger(host.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("IOException");
}finally{
try {
System.out.println("closing socket");
out.close();
hostThreadSocket.close();
} catch (IOException ex) {
System.out.println("Other IOException");
Logger.getLogger(host.class.getName()).log(Level.SEVERE, null, ex);
}
}
哪些是有效的方式:
在Java文件中没有发现错误(据我所见)
连接建立
不:
- 任何一端都没有消息
我试着包括尽可能少的代码,如果更多是需要的,我会编辑的问题。对于修复或调试此问题的任何帮助都将非常感谢。
客户端和服务器都在等待对方开始通信