I've been trying to solve this simple problem, but I cannot make it work.
I am using WebSocketSharp.Server. The code can be seen below.
In my NetworkClass I have someData I would like to send to the client when a message is received. The problem is the OnMessage event gets fired in a different class, and I don't know how the access the instance of this class.
Broadcasting to all clients form the NetworkClass works fine and receiving messages form the client works fine as well.
public class IndexRoute : WebSocketBehavior {
protected override void OnMessage(MessageEventArgs e) {
Console.WriteLine("Received message form client: "+e.Data);
//TODO: send someData string to client
}
}
public class NetworkClass {
String someData = "TestData";
WebSocketServer server = new WebSocketServer("ws://127.0.0.1:5000");
public NetworkClass() {
server.AddWebSocketService<IndexRoute>("/");
server.Start();
Console.WriteLine("Server started");
}
public void broadcastData() {
server.WebSocketServices["/"].Sessions.Broadcast(someData);
Console.WriteLine("Broadcast");
}
}
I combined the answers of Jeroen van Langen and Jesper. The key was to pass the instance of the
NetworkClassto theIndexRouteclass and access the variables from there.server.AddWebSocketService<IndexRoute>("/", () => new IndexRoute(this));works but is marked as obsolete.