Samples

Nugget Documentation

The Server

Server instantiation

The server is instantiated with the following constructor:
var wss = new WebSocketServer(int port, string origin, string location);
where
  • port is the port the server should run on/listen to
  • origin is the origin of the connections i.e. the url of the client script.
  • location is the location of the server e.g. ws://localhost:port/somewhere

Handeling connections

After the server object is instantiated handler classses are registered to handle the incomming connections:
wss.RegisterHandler<HandlerClass>("/somePath");

By registering HandlerClass with the path "/somePath", every conenction to the server at this path will be handled by a HandlerClass object. A new HandlerClass object is for every new connection to the server. It is posible to register several handler classes, but only one class per path. A handler class must inherit from Nugget.WebSocket.

Here is an example of such a handler class:
class HandlerClass : WebSocket
{
   public override void connected()
   {
      Console.WriteLine("new connection!");
   }

   public override void Incoming(string data)
   {
      Console.WriteLine("recieved data: "+data);
   }

   public override void Disconnected()
   {
      Console.WriteLine("disconnected");
   }
}

Handler classes must implement the abstract methods specified in the WebSocket class.
  • Connected() - this method is called after the connection has been established
  • Incoming(string data) - this method is called when data is received from the client, the data is passsed in the "data" argument.
  • Disconnected() - this method is called when the client is disconnected.

Sending data

To send data use the Send(string data) method on the WebSocket class, this method will send the data string to the client that the WebSocket object is assosiated to.

The following example sends the message "Welcome" to the clients after they have connected.
public override void connected()
{
   Send("Welcome!");
}

The client

The client code is written in JavaScript, and is not specific to this implementation, but a part of HTML5:

Connection to the server:
var ws = new WebSocket("server_location");

Events:
ws.onopen = function () {
    // the connection has been established
};
 
ws.onmessage = function (evt) {  
    // a message (evt.data) has been received from the server
};
 
ws.onclose = function () {
    // the connection has been closed
};

Last edited Sep 14, 2010 at 5:54 PM by jonlt, version 11

Comments

No comments yet.