Connecting to a node.js server from C#

11,131

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 - http://socketio4net.codeplex.com

Share:
11,131

Related videos on Youtube

Josh Santangelo
Author by

Josh Santangelo

Updated on September 15, 2022

Comments

  • Josh Santangelo
    Josh Santangelo over 1 year

    I'm trying to write a simple server that .NET clients can connect to to exchange messages. 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. 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.

    My client code (pasted below) is very similar to the example code for the Socket class, but it's behaving strangely. In the "ProcessConnect" handler, e.LastOperation == "Connect", and e.SocketError == "Success", but the connection event handler on the server side is not firing. Also weird is that when the code sends "Hello World", the receive handler also gets fired with "Hello World" coming back. 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.

    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');
    });
    
  • Josh Santangelo
    Josh Santangelo over 11 years
    That looks very helpful! Only problem is I need to compile it for Silverlight. Looks like this uses a number of classes not available there. Maybe I can port it...