我目前正在学习在Java中使用套接字,但无法设法在套接字之间发送数据,在本例中是在android和计算机之间(如果相关的话)。我使用的方法来自here .
请原谅不良的代码格式。
客户端:
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 文件中都没有发现错误(据我所知)
连接已建立
什么不:
- 两端均未看到任何消息
我尝试包含尽可能少的代码,如果需要更多代码,我将编辑问题。任何有关修复或调试此问题的帮助将不胜感激。
最佳答案
您的客户端和服务器都在等待对方开始通信。
关于java - 使用 PrintWriter 通过 Java 套接字发送数据不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32072902/