将node.js服务器接收的数据打印到控制台

时间:2014-04-16 02:15:12

标签: java javascript node.js

我有一个java类将数据发送到node.js服务器......

    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);

成功收听并连接

如何在服务器端控制台上打印发送到服务器的数据?

我被告知太多的代码和没有足够的细节发布所以这是我只是说要允许我发布的东西,因为这就是我所拥有的所有信息。

1 个答案:

答案 0 :(得分:1)

问题在于您正在聆听数据&#39;在服务器本身而不是每个传入连接。你想要这个:

// ...

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);