简体   繁体   English

从C#连接到node.js服务器

[英]Connecting to a node.js server from C#

I'm trying to write a simple server that .NET clients can connect to to exchange messages. 我正在尝试编写一个.NET客户端可以连接到的简单服务器来交换消息。 Any message from any client will go to all of the others. 来自任何客户的任何消息都将发送给所有其他客户。 node.js + socket.io seems like a good way to go here, but I'm having trouble. node.js + socket.io似乎是一个很好的方式去这里,但我遇到了麻烦。 I'm using sample code from the socket.io site, and when I connect to it from a browser, the console traces out all the connection and heartbeat events as it should, so I think I've at least got the environment setup correctly. 我正在使用来自socket.io站点的示例代码,当我从浏览器连接到它时,控制台会按原样跟踪所有连接和心跳事件,因此我认为我至少已正确设置了环境。

My client code (pasted below) is very similar to the example code for the Socket class, but it's behaving strangely. 我的客户端代码(粘贴在下面)与Socket类的示例代码非常相似,但它表现得很奇怪。 In the "ProcessConnect" handler, e.LastOperation == "Connect", and e.SocketError == "Success", but the connection event handler on the server side is not firing. 在“ProcessConnect”处理程序中,e.LastOperation ==“Connect”和e.SocketError ==“Success”,但服务器端的连接事件处理程序未触发。 Also weird is that when the code sends "Hello World", the receive handler also gets fired with "Hello World" coming back. 同样奇怪的是,当代码发送“Hello World”时,接收处理程序也会因“Hello World”回来而被解雇。 I know this isn't coming from the server because there's no code on the server to do this. 我知道这不是来自服务器,因为服务器上没有代码可以执行此操作。 I thought maybe the socket was connecting to itself or something, but if I shut the server down, the connection fails. 我想也许套接字连接到自身或其他东西,但如果我关闭服务器,连接失败。

Clearly there's something basic I'm missing about .NET sockets, but I'm not sure what it is. 显然,我缺少一些关于.NET套接字的基本内容,但我不确定它是什么。

Client: 客户:

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

Server: 服务器:

var io = require('socket.io').listen(81);

io.sockets.on('connection', function (socket) {
    console.log('connected yo');
});

You could try handle this using your own socket code. 您可以尝试使用自己的套接字代码来处理它。 I would recommend that you use a library like SocketIO4Net to handle the integration with .Net 我建议您使用像SocketIO4Net这样的库来处理与.Net的集成

SocketIO4Net - http://socketio4net.codeplex.com SocketIO4Net - http://socketio4net.codeplex.com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM