Java クラスから Node.js に連続データを送信しようとしていますが、それらをすべてキャッチすることはできません。Java から送信された最初のデータしか受信できません。 NodeJs が Java クラスから連続データをキャッチできるようにコードを作成します。
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);