[英]Why is this node.js tcp server not writing back to Java client until it closes?
這是我發現用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();
}
}
啟動客戶端時,從客戶端獲得的唯一輸出是很多次的“寫消息”和“等待回復”。 當我關閉服務器時,我終於收到您說“ Hellow world”的響應,並且通常會插入一兩個空值。 至於服務器,它可以很好地打印出兩個打印語句。 您認為有人可以在這里幫助我嗎?
Java客戶端使用in.readLine()
在輸入流中查找換行符。 但是,服務器沒有將換行符寫入客戶端套接字。
所以改變這個:
sock.write('You said "' + data + '"');
對此:
sock.write('You said "' + data + '"\n');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.