0

我正在尝试将我的 Java 类中的连续数据发送到 Node.js。但我无法全部捕获它们。我只收到从 Java 发送的第一个数据。这是我的 Java 类和 NodeJs。我想编写代码,以便 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();
        }
        }

节点.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);
4

1 回答 1

2

收到第一条消息时,您将删除数据侦听器。删除它,它应该可以工作。

var firstDataListenner = function (data) {
        fileData = data;
    console.log('Received namespace from java End: ' + data);
    //javaServer.send(data);
}
于 2012-12-18T12:54:18.493 回答