gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:08:19 25 4
gpt4 key购买 nike

我有一个 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);

它成功监听并连接,

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

我被告知代码太多,没有足够的细节来发布,所以这只是我说的一些内容,以便我可以发布,因为这就是我所拥有的所有信息。

最佳答案

问题在于您正在监听服务器本身的“数据”,而不是每个传入连接。你想要这个:

// ...

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

关于java - 将node.js服务器接收到的数据打印到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23097819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com