我有一个NodeJs服务器,可以通过OutputStream从Java客户端接收数据。但是,如何将数据从NodeJs本身发送到客户端,并让Java读取接收到的数据?假设服务器要向客户端发送响应消息。我应该在客户端和服务器上添加什么?
我在NodeJs服务器上添加了一些代码以通过套接字发送数据,但我认为这是不对的。
我的NodeJs代码
const javaServer = require('net').createServer();
const WebSocket = require('ws');
const wss = new WebSocket.Server({port:8286});
...
javaServer.on('connection', (javaSocket) => {
var clientAddress = javaSocket.address().address + ':' +
javaSocket.address().port;
console.log (`Java ${clientAddress} connected!`);
var firstDataListener = (data) => {
fileData = data;
console.log ('Received from Java End : ' + data);
};
javaSocket.on('data', firstDataListener);
javaSocket.on('close', ()=>{
console.log(`Java ${clientAddress} disconnected.`);
});
});
wss.on('connection', function connection(ws){
ws.send("Hello, Client!");
});
javaServer.listen(javaPort);
我的Java端
public static void main(String[] args) {
try {
Socket nodejs = new Socket("127.0.0.1", 8285);
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 ex) {
ex.printStackTrace();
}
}
public static void sendMessage(Socket s, String message) throws IOException
{
System.out.println("Send Msg: " + message);
s.getOutputStream().write(message.getBytes("UTF-8"));
s.getOutputStream().flush();
}