采用自定义配置启动的访问使用
app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="superSocket" type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine"/>
</configSections>
<appSettings>
<add key="ServiceName" value="SuperWebSocket"/>
</appSettings>
<superSocket>
<servers>
<server name="SuperWebSocket"
serverTypeName="CmdSocket" textEncoding="UTF-8" maxRequestLength="10240" maxConnectionNumber="20000" keepAliveTime="60" keepAliveInterval="20" receiveBufferSize="4096">
<listeners>
<add ip="192.168.1.200" port="9999"/>
</listeners>
</server>
</servers>
<serverTypes>
<add name="CmdSocket"
type="websocket.CmdServer, websocket" />
</serverTypes>
</superSocket>
</configuration>
<add ip="192.168.1.200" port="9999"/>
和 maxRequestLength 这两个需要设置,否则很容易出错。
cmdserver:
using SuperWebSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace websocket
{
public class CmdServer : WebSocketServer<CmdSession>
{
public CmdServer()
{
}
}
}
CmdSession:
using SuperSocket.SocketBase;
using SuperWebSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace websocket
{
public class CmdSession : WebSocketSession<CmdSession>
{
protected override void OnSessionStarted()
{
base.OnSessionStarted();
var str = Util.getJsonStr("log", new { sessionid = this.SessionID });
//回传sessionid
this.Send(str);
}
protected override void OnSessionClosed(CloseReason reason)
{
base.OnSessionClosed(reason);
if (reason == CloseReason.ServerShutdown)
return;
Util._onLineUsers.Remove(this.SessionID);
if (Util._onLineUsers.Count > 0)
{
string str = Util.getJsonStr("userlist", Util.onlineUserList());
foreach (var s in this.AppServer.GetAllSessions())
{
s.Send(str);
}
}
}
}
}
CMD:
using SuperWebSocket.SubProtocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace websocket
{
public class CMD : SubCommandBase<CmdSession>
{
public override void ExecuteCommand(CmdSession session, SubRequestInfo requestInfo)
{
try
{
Newtonsoft.Json.Linq.JObject jobj = Newtonsoft.Json.Linq.JObject.Parse(requestInfo.Body);
string cmd = jobj["cmd"].ToString();
Newtonsoft.Json.Linq.JObject jdata = (Newtonsoft.Json.Linq.JObject)jobj["data"];
switch (cmd)
{
case "log":
OnlineUser ou = new OnlineUser();
ou.UserName = jdata["username"].ToString();
ou.RealName = jdata["realname"].ToString();
OnlineUser oo = Util._onLineUsers.FirstOrDefault(f => f.Value.UserName == ou.UserName).Value;
if (oo == null)
{
Util._onLineUsers.Add(session.SessionID, ou);
}
//给所有用户发送在线用户名单
string str = Util.getJsonStr("userlist", Util.onlineUserList());
foreach (var s in session.AppServer.GetAllSessions())
{
s.Send(str);
}
break;
case "listuser":
session.Send(Util.getJsonStr("userlist", Util.onlineUserList()));
break;
}
}
catch (Exception e)
{
session.Send(Util.getJsonStr("err", e.Message));
}
}
}
}
工具类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace websocket
{
class Util
{
public static Dictionary<string, OnlineUser> _onLineUsers = new Dictionary<string, OnlineUser>();
public static string getJsonStr(string cmd, object data)
{
var result = new
{
cmd = cmd,
data = data
};
string str = Newtonsoft.Json.JsonConvert.SerializeObject(result);
return str;
}
public static List<object> onlineUserList()
{
List<object> list = new List<object>();
foreach (KeyValuePair<string, OnlineUser> key in _onLineUsers)
{
list.Add(new { sessionid = key.Key, user = key.Value });
}
return list;
}
}
}
主程序:
using SuperSocket.SocketBase;
using SuperSocket.SocketEngine;
using SuperWebSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace websocket
{
class Program
{
static void Main(string[] args)
{
var bootstrap = BootstrapFactory.CreateBootstrap();
if (!bootstrap.Initialize())
{
Console.WriteLine("服务器初始化错误,请查看错误日志");
Console.ReadKey();
return;
}
var result = bootstrap.Start();
Console.WriteLine("启动: {0}!", result);
if (result == StartResult.Failed)
{
Console.WriteLine("启动失败!请查看错误日志");
Console.ReadKey();
return;
}
Console.WriteLine("按 'q' 退出!");
while (Console.ReadKey().KeyChar != 'q')
{
Console.WriteLine();
continue;
}
Console.WriteLine();
//Stop the appServer
bootstrap.Stop();
}
}
}