Reputation: 32
I have a java class sending data to a node.js server...
import java.io.*;
import java.net.Socket;
public class TestingServer
{
public static void main(String[] args)
{
try
{
String testData = " Test data...";
Socket nodejs = new Socket("localhost", 8080);
Thread.sleep(100);
for(int i = 1; i < 100; i++)
{
//Thread.sleep(400);
sendMessage(nodejs, i + testData + " ");
System.out.println(i + " <----Message sent to server");
}
}
catch (Exception e)
{
System.out.println("Server closed...oops");
e.printStackTrace();
}
}
public static void sendMessage(Socket s, String message) throws IOException
{
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 , javaSocket = 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 firstDataListener = function(data){
fileData = data;
console.log('Data recieved from java: ' + fileData);
}
javaSocket.on('data', firstDataListener);
javaSocket.on('close', function(){
console.log('Java ' + clientAddress + ' disconnected');
});
javaServer.listen(javaPort);
It successfully listens, and connects,
How do i print the data sent to the server on the server side console?
I was told theres too much code and not enough detail to post so this is me just saying stuff to allow me to post, because thats all the information i have.
Upvotes: 0
Views: 2295
Reputation: 106746
The problem is that you're listening for 'data' on the server itself instead of each incoming connection. You want this instead:
// ...
javaServer.on('connection', function(javaSocket){
var clientAddress = javaSocket.address().address+':'+javaSocket.address().port;
console.log('Java ' + clientAddress + ' connected');
javaSocket.on('data', function(data){
fileData = data;
console.log('Data recieved from java: ' + fileData);
}).on('close', function() {
console.log('Java ' + clientAddress + ' disconnected');
});
});
javaServer.listen(javaPort);
Upvotes: 1