Create a winform Application:
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!
First websocket example worked. Thanks.
How would you send Json to the server though?
private void button1_Click(object sender, EventArgs e)
{
var json = “{\”op\”:\”unconfirmed_sub\”}”;
client.Send(json);
}
Does not seem to work?
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”
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.’
Refer to this answer.
That worked. Thanks.
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.
I get connected successfully but the message sent is not echoed back, even after adding the cross-thread fix. What’s wrong?
Sorry, my bad, my listBox1 was not set up correctly to add items. Now it’s echoing just fine. Thank you.
whats the notation for web socket using an ip address, I used “wss://192.168.10.1:9998” and having problems connecting. Thanks
I’s possible to change, on the fly, the websockets server, in a winform application?
how to get the websocket json data in c# windows form…
Pingback: sta/websocket-sharp库winform客户端简单例子(一) – 毛毛编程