websocket-sharp/Example2/Chat.cs

52 lines
1019 B
C#
Raw Normal View History

2012-08-06 13:34:39 +08:00
using System;
2012-10-26 13:58:50 +08:00
using System.Threading;
2012-08-06 13:34:39 +08:00
using WebSocketSharp;
using WebSocketSharp.Server;
namespace Example2
{
2012-08-06 13:34:39 +08:00
public class Chat : WebSocketService
{
2012-10-26 13:58:50 +08:00
private static int _num = 0;
private string _name;
private string _prefix;
public Chat ()
2013-12-03 14:45:14 +08:00
: this (null)
{
}
public Chat (string prefix)
{
2014-03-31 16:10:45 +08:00
_prefix = !prefix.IsNullOrEmpty () ? prefix : "anon#";
}
private string getName ()
{
2014-03-31 16:10:45 +08:00
var name = Context.QueryString ["name"];
return !name.IsNullOrEmpty () ? name : (_prefix + getNum ());
}
2014-01-04 01:42:03 +08:00
private static int getNum ()
{
return Interlocked.Increment (ref _num);
}
protected override void OnOpen ()
{
_name = getName ();
}
protected override void OnMessage (MessageEventArgs e)
{
Sessions.Broadcast (String.Format ("{0}: {1}", _name, e.Data));
}
protected override void OnClose (CloseEventArgs e)
2012-08-06 13:34:39 +08:00
{
Sessions.Broadcast (String.Format ("{0} got logged off...", _name));
2012-08-06 13:34:39 +08:00
}
}
}