gpt4 book ai didi

javascript - 为什么这个 Node.js tcp 服务器在关闭之前不会写回 Java 客户端?

转载 作者:行者123 更新时间:2023-12-03 11:20:24 25 4
gpt4 key购买 nike

Here是我发现的用node.js编写的tcp服务器的示例:

net.createServer(function(sock) {

// We have a connection - a socket object is assigned to the connection automatically
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);

// Add a 'data' event handler to this instance of socket
sock.on('data', function(data) {

console.log('DATA ' + sock.remoteAddress + ': ' + data);
// Write the data back to the socket, the client will receive it as data from the server
sock.write('You said "' + data + '"');

});

// Add a 'close' event handler to this instance of socket
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});

}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);

我试图使用它作为 tcp 服务器的基础,该服务器必须同时处理多个传入连接。这是我编写的一个 Java 程序来测试这一点:

public static final String MESSAGE = "Hellow world";
public static Semaphore networkLock;

public static void main(String[] args)
{
//writeMessage(MESSAGE);

Thread[] threadPool = new Thread[10];
networkLock = new Semaphore(1);

for (int i = 0; i < threadPool.length; i++)
{
threadPool[i] = new Thread(new Runnable() {

@Override
public void run() {
writeMessage(MESSAGE);

}
});

threadPool[i].start();
}

}

public static void writeMessage(String test)
{
try {
if(sock == null || sock.isClosed())
sock = new Socket(HOST, PORT);

DataOutputStream out =
new DataOutputStream(sock.getOutputStream());
System.out.println("Writting message");

//networkLock.acquire();
out.writeUTF(test);
//networkLock.release();

BufferedReader in = new BufferedReader(
new InputStreamReader(sock.getInputStream()));

System.out.println("Waiting for reply");
String input = in.readLine();

System.out.println(input);
// in.close();
// out.close();
// sock.close();

} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

当我启动客户端时,我从客户端得到的唯一输出是多次“正在写入消息”和“正在等待回复”。当我关闭服务器时,我终于得到了 You said“Hello world” 的响应,并且通常会抛出一个或两个 null 。至于服务器,它打印出两条打印语句就很好了。你认为有人可以帮助我吗?

最佳答案

Java 客户端使用 in.readLine() 在输入流中查找换行符。但是,服务器不会向客户端套接字写入换行符。

所以改变这个:

sock.write('You said "' + data + '"');

对此:

sock.write('You said "' + data + '"\n');

关于javascript - 为什么这个 Node.js tcp 服务器在关闭之前不会写回 Java 客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27142487/

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