I am trying to send a continuous data from my Java class to Node.js.But I am unable to catch them all.I only receive the first one which get sent from Java..Here is my Java class and NodeJs.I want to make code such that NodeJs may able to catch continuous data from 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);
You are removing the data listener when the first message is received. Remove that and it should work.
var firstDataListenner = function (data) {
fileData = data;
console.log('Received namespace from java End: ' + data);
//javaServer.send(data);
}