RSS

C# Websocket programming: the simplest example

23 Jul

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!

Advertisements
 
4 Comments

Posted by on July 23, 2015 in Dotnet/C#, Programming

 

Tags: , , , , , , , ,

4 responses to “C# Websocket programming: the simplest example

  1. Harry

    November 23, 2015 at 4:32 pm

    First websocket example worked. Thanks.

     
  2. Someday Soon (RoyalVlogger)

    June 10, 2016 at 11:16 pm

    How would you send Json to the server though?

     
  3. Someday Soon (RoyalVlogger)

    June 10, 2016 at 11:17 pm

    private void button1_Click(object sender, EventArgs e)
    {
    var json = “{\”op\”:\”unconfirmed_sub\”}”;
    client.Send(json);
    }

    Does not seem to work?

     
  4. Nick F

    March 13, 2017 at 8:26 pm

    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”

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: