C# Websocket programming: the simplest example


Create a winform Application:

image

Download the Websocket-Sharp from Nuget:

PM> Install-Package WebSocketSharp -Pre

Add below code:

        private WebSocket client;
        const string host = “wss://echo.websocket.org”;

        private void Form1_Load(object sender, EventArgs e)
        {
            client = new WebSocket(host);

            client.OnOpen += (ss, ee) =>
               listBox1.Items.Add(string.Format(“Connected to {0} successfully “, host));
            client.OnError += (ss, ee) =>
               listBox1.Items.Add(”     Error: “ + ee.Message);
            client.OnMessage += (ss, ee) =>
               listBox1.Items.Add(“Echo: “ + ee.Data);
            client.OnClose += (ss, ee) =>
               listBox1.Items.Add(string.Format(“Disconnected with {0}”, host));
        }

Add below button click event handler:

        private void SendButton_Click(object sender, EventArgs e)
        {
            var content = inputBox.Text;
            if(!string.IsNullOrEmpty(content))
                client.Send(content);
        }

        private void ConnectButton_Click(object sender, EventArgs e)
        {
            client.Connect();
        }

        private void DisconnectButton_Click(object sender, EventArgs e)
        {
            client.Close();
        }

That is it! Run your app and enjoy!

14 thoughts on “C# Websocket programming: the simplest example

  1. Nick F

    I can only connect when I use ws://echo.websocket.org. When I send the message, it fails at the line client.OnMessage += (ss, ee) => listBox1.Items.Add(” Echo: ” + ee.Data); – I get “an error occured in sending the data”

  2. Mike Lowry

    Using nuget install of WebSocketSharp:
    At the client.OnMessage event I am getting an error: “System.InvalidOperationException: ‘Cross-thread operation not valid: Control ‘listBox1′ accessed from a thread other than the thread it was created on.’

  3. Mike Lowry

    Can you offer advice on how to structure a form that has an interactive transaction (like the example) in one panel, and a running multi-receive panel in the other, e.g., a discussion forum that updates as new items are posted? Need to have all on the same connection, with a decision on message receipt as to which control to post to.

  4. RoySeberg

    I get connected successfully but the message sent is not echoed back, even after adding the cross-thread fix. What’s wrong?

  5. ernesto

    whats the notation for web socket using an ip address, I used “wss://192.168.10.1:9998” and having problems connecting. Thanks

  6. Pingback: sta/websocket-sharp库winform客户端简单例子(一) – 毛毛编程

Leave a comment