Java 和 Node.js 之间的通信问题(基于 TCP/IP)
我用 Node.js 建了一个 tcpserver,然后用 Java 的 socket 去连接,结果 Java 这边可以把信息完整无误的发给 Node.js 这边,但是 Node.js 返回的数据始终读不到
private void initConnection() {
if (!isRun)
return;
try {
Log.i(TAG, "连接中……");
socketClient = new Socket(_ip, _port);
int timeout = 10000;
socketClient.setSoTimeout(timeout);// 设置阻塞时间
Log.i(TAG, "连接成功");
bufferedReader = new BufferedReader(new InputStreamReader(
socketClient.getInputStream()));
printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socketClient.getOutputStream())), true);
Log.i(TAG, "输入输出流获取成功");
} catch (UnknownHostException e) {
Log.i(TAG, "连接错误UnknownHostException 重新获取");
e.printStackTrace();
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
initConnection();
} catch (IOException e) {
Log.i(TAG, "连接服务器io错误");
e.printStackTrace();
} catch (Exception e) {
Log.i(TAG, "连接服务器错误Exception" + e.getMessage());
e.printStackTrace();
}
}
读取部分
while (isRun) { try { if (socketClient != null) { if (bufferedReader == null) { return; } while ((line = bufferedReader.readLine()) != null) { System.out.println(line); }
} else { initConnection(); } } catch (Exception e) { Log.i(TAG, "数据接收错误" + e.getMessage()); if (!(e instanceof SocketTimeoutException)) { initConnection(); } } }