I'm trying to do a simple WebSocket Server in C# that will communicate with a Client in JavaScript, the code I am testing is this:
Websocket-sharp Server
using System;
using System.Windows.Forms;
using WebSocketSharp;
using WebSocketSharp.Server;
namespace MyProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var wssv = new WebSocketServer(8081);
wssv.WaitTime = TimeSpan.FromSeconds(3);
wssv.AddWebSocketService<NFP>("/");
wssv.Start();
}
}
public class NFP : WebSocketBehavior
{
protected override void OnMessage(MessageEventArgs e)
{
Console.WriteLine(e.Data);
Send("Received");
}
protected override void OnError(ErrorEventArgs e)
{
//Console.WriteLine(e.Exception);
}
protected override void OnClose(CloseEventArgs e)
{
//Console.WriteLine(e.Code);
}
}
}
Now I was wondering, how do I send the message received at OnMessage for the ListBox that is on Form1 already open?
Define the target listbox as a property for your NPF class:
public ListBox Target {get; set;}
set the target in your button1_Click method:
wssv.Target = myListBox;
When you receive the message add it to the listbox. However, since you are in a different Thread to the UI Thread (which is the only one that may modify controls on the Form), you have to call the Invoke
member on the Target
to do your work:
protected override void OnMessage(MessageEventArgs e)
{
Console.WriteLine(e.Data);
if (Target != null)
Target.Invoke( () => {Target.Items.Add(e.Message);});
Send("Received");
}