我正在尝试编写一个简单的服务器,.NET 客户端可以连接到该服务器以交换消息。来自任何客户端的任何消息都会发送给所有其他客户端。node.js + socket.io 似乎是去这里的好方法,但我遇到了麻烦。我正在使用来自 socket.io 站点的示例代码,当我从浏览器连接到它时,控制台会按照应有的方式跟踪所有连接和心跳事件,所以我认为我至少已经正确设置了环境.
我的客户端代码(粘贴在下面)与 Socket 类的示例代码非常相似,但它的行为很奇怪。在 "ProcessConnect" 处理程序中,e.LastOperation == "Connect" 和 e.SocketError == "Success",但服务器端的连接事件处理程序没有触发。同样奇怪的是,当代码发送“Hello World”时,接收处理程序也会随着“Hello World”返回而被触发。我知道这不是来自服务器,因为服务器上没有执行此操作的代码。我以为套接字可能正在连接到自身或其他东西,但是如果我关闭服务器,连接就会失败。
显然,我缺少一些关于 .NET 套接字的基本知识,但我不确定它是什么。
客户:
public class NodeClient
{
Socket _Socket;
public NodeClient()
{
SocketAsyncEventArgs socketState = new SocketAsyncEventArgs();
socketState.Completed += SocketState_Completed;
socketState.RemoteEndPoint = new DnsEndPoint("localhost", 81);
_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_Socket.ConnectAsync(socketState);
}
private void SocketState_Completed(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError != SocketError.Success)
{
throw new SocketException((int)e.SocketError);
}
switch (e.LastOperation)
{
case SocketAsyncOperation.Connect:
ProcessConnect(e);
break;
case SocketAsyncOperation.Receive:
ProcessReceive(e);
break;
case SocketAsyncOperation.Send:
ProcessSend(e);
break;
default:
throw new Exception("Invalid operation completed.");
}
}
// Called when a ConnectAsync operation completes
private void ProcessConnect(SocketAsyncEventArgs e)
{
byte[] buffer = Encoding.UTF8.GetBytes("Hello World");
e.SetBuffer(buffer, 0, buffer.Length);
bool willRaiseEvent = _Socket.SendAsync(e);
if (!willRaiseEvent)
{
ProcessSend(e);
}
}
// Called when a ReceiveAsync operation completes
private void ProcessReceive(SocketAsyncEventArgs e)
{
string message = Encoding.UTF8.GetString(e.Buffer, 0, e.Buffer.Length);
}
// Called when a SendAsync operation completes
private void ProcessSend(SocketAsyncEventArgs e)
{
bool willRaiseEvent = _Socket.ReceiveAsync(e);
if (!willRaiseEvent)
{
ProcessReceive(e);
}
}
}
服务器:
var io = require('socket.io').listen(81);
io.sockets.on('connection', function (socket) {
console.log('connected yo');
});