1
我可以在本地主機上的TCP客戶端和TCP服務器之間建立TCP連接,但是我不能重複同一個網絡範圍內不同計算機連接的示例(發件人Windows服務器2012 x64 R2和接收器Windows 10 x64專業版)。 TCP服務器是C#應用程序,TCP客戶端在node.js中。我禁用了防病毒和Windows防火牆。TCP服務器只能在localhost方案中工作
//SERVER C#
void Receive() {
//tcp_Listener = new TcpListener(IPAddress.Parse("192.168.1.62"), 212);
IPAddress localAddr = IPAddress.Parse("0.0.0.0");
tcp_Listener = new TcpListener(localAddr,212);
TcpClient clientSocket = default(TcpClient);
tcp_Listener.Start();
print("Server Start");
while (mRunning)
{
// check if new connections are pending, if not, be nice and sleep 100ms
if (!tcp_Listener.Pending()){
Thread.Sleep(10);
}
else {
clientSocket = tcp_Listener.AcceptTcpClient();
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
if (dataFromClient != "") {
print ("Data from client: " + dataFromClient);
} else {
print ("Client no data");
}
clientSocket.Close();
}
}
}
//CLIENT NodeJS
var net = require('net');
var HOST = '192.168.0.136';
var PORT = 212;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('MSG SENT!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
Wireshark的日誌關於整個連接如下:
這是TCP客戶端日誌:
與您當前的問題沒有關係,但是您的服務器代碼已損壞。 'Read'返回*有多少*字節已經放入緩衝區,並且您需要確保不使用緩衝區中實際不包含任何接收數據的部分。 –
爲什麼你直接在服務器和客戶端都關閉**摧毀**?我認爲這會造成問題,特別是在客戶端的CallBack中被摧毀。 –
@Bewar Salah我已經刪除了客戶端的破壞,錯誤仍然存在 – JosepB