我正在尝试将连续数据从我的Java类发送到Node.js.But我无法捕获它们。我只收到第一个从Java发送的数据。这是我的Java类和NodeJs。我想编写代码,以便NodeJ可以从Java Class中捕获连续数据。
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.io.*;
class NodeCommunicator {
public static void main(String[] args) {
try {
Socket nodejs = new Socket("localhost", 8080);
Thread.sleep(100);
for(int i=1; i< 100; i++){
Thread.sleep(500);
sendMessage(nodejs, i + " ");
System.out.println(i + " has been sent to server");
}
} catch (Exception e) {
System.out.println("Server Closed..Something went Wrong..");
e.printStackTrace();
}
}
public static void sendMessage(Socket s, String message) throws IOException {
System.out.println("In SendMesage"+message);
s.getOutputStream().write(message.getBytes("UTF-8"));
s.getOutputStream().flush();
}
}
Node.js的
var javaPort = 8080;
var javaServer = require('net').createServer();
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({port: 90});
var fileData ;
console.log('=====================================================');
console.log('Node.js/Java Communication Module');
console.log('=====================================================');
javaServer.on('listening', function () {
console.log('Server is listening on ' + javaPort);
});
javaServer.on('error', function (e) {
console.log('Server error: ' + e.code);
});
javaServer.on('close', function () {
console.log('Server closed');
});
javaServer.on('connection', function (javaSocket) {
var clientAddress = javaSocket.address().address + ':' + javaSocket.address().port;
console.log('Java ' + clientAddress + ' connected');
var firstDataListenner = function (data) {
fileData = data;
console.log('Received namespace from java End: ' + data);
//javaServer.send(data);
javaSocket.removeListener('data', firstDataListenner);
}
javaSocket.on('data', firstDataListenner);
javaSocket.on('close', function() {
console.log('Java ' + clientAddress + ' disconnected');
});
});
javaServer.listen(javaPort);
答案 0 :(得分:2)
收到第一条消息时,您正在删除数据侦听器。删除它,它应该工作。
var firstDataListenner = function (data) {
fileData = data;
console.log('Received namespace from java End: ' + data);
//javaServer.send(data);
}