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!
Filed under: Dotnet/C#, Programming Tagged: .net, C#, example, snapshot, Socket, step by step, tutorial, Websocket, Websocket-Sharp
