HTML and CSS Reference
In-Depth Information
// List of connections
List<WsConnection>_unknown;
#endregion Members
public WsServer(int port)
{
_port=port;
// This is a list of active connections
_unknown=new List<WsConnection>();
}
public void StartSocketServer()
{
// Create a socket that will listen for messages
_listener=new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.IP);
// Create and bind the endpoint
IPEndPoint ip=new IPEndPoint(IPAddress.Loopback, _port);
_listener.Bind(ip);
// Listen for new connections - the OnConnect() method
// will be invoked to handle them
_listener.Listen(100);
_listener.BeginAccept(new AsyncCallback(OnConnect), null);
}
void MessageReceived(WsConnection sender, MessageReceivedEventArgs e)
{
string msg=e.Message;
Console.WriteLine(msg);
sender.SendMessage("echo: "+msg);
}
void Disconnected(WsConnection sender, EventArgs e)
{
_unknown.Remove(sender);
Console.WriteLine("Client has disconnected");
}
}
}
The StartSocketServer() method is called to put the server to work. It creates a Socket object and
configures it using the specified port. This method is hard-coded to use the localhost address. Once the end
point is configured, the Socket object's BeginAccept() method is called. This will invoke the specified callback
method ( OnConnect ) when a new connection is received. The MessageReceived() event handler simply writes
the input message to the console and echoes the message back to the client. The WsConnection object that
 
Search WWH ::




Custom Search