websocket-sharp/Example2/Chat.cs
2014-03-31 17:10:45 +09:00

52 lines
1019 B
C#

using System;
using System.Threading;
using WebSocketSharp;
using WebSocketSharp.Server;
namespace Example2
{
public class Chat : WebSocketService
{
private static int _num = 0;
private string _name;
private string _prefix;
public Chat ()
: this (null)
{
}
public Chat (string prefix)
{
_prefix = !prefix.IsNullOrEmpty () ? prefix : "anon#";
}
private string getName ()
{
var name = Context.QueryString ["name"];
return !name.IsNullOrEmpty () ? name : (_prefix + getNum ());
}
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)
{
Sessions.Broadcast (String.Format ("{0} got logged off...", _name));
}
}
}