SuperSocket配置UDP服務器
零、需求
- 兩個設備局域網聯機,需要用廣播自動搜尋,而SuperSocket1.6的默認AppServer使用的是TCP,但只有UDP才支持廣播。
一、解決
1. 方案一:可以通過配置 “App.config” 文件,再使用 “BootstrapFactory” 來啟動UDP服務器。(這個是參考了C#SuperSocket的搭建--通過配置啟動的)
- 編寫自己的 “Session” 類,我這邊隨便寫寫
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SuperSocketTest.src.Service.UDPServer
{
//這邊權限要public,不然在接下來的命令類那邊是會報錯的
public class MySession : AppSession<MySession>
{
protected override void OnSessionStarted()
{
//連接后發送歡迎信息
this.Send("Welcome to SuperSocket Telnet Server");
}
protected override void HandleUnknownRequest(StringRequestInfo requestInfo)
{
//無法解析命令提示未知命令
this.Send("Unknow request");
}
protected override void HandleException(Exception e)
{
//程序異常信息
this.Send("Application error: {0}", e.Message);
}
protected override void OnSessionClosed(CloseReason reason)
{
//連接被關閉時
base.OnSessionClosed(reason);
}
}
}
- 接着按自己需求定義自己APPServer,這邊我也隨便寫寫(自定義的AppServer,在繼承AppServer是的Session泛型,記得要更改為我們自定義的Session,這邊我的是MySession)
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SuperSocketTest.src.Service.UDPServer
{
class MyServer : AppServer<MySession>
{
//這邊Base里留空就是默認的命令行編碼和用空格分隔
//這邊我把命令與參數之間的分隔符改為“:”,把參數之間的分隔符改為“,”
public MyServer()
: base(new CommandLineReceiveFilterFactory(Encoding.Default, new BasicRequestInfoParser(":", ",")))
{
}
protected override bool Setup(IRootConfig rootConfig, IServerConfig config)
{
return base.Setup(rootConfig, config);
}
protected override void OnStopped()
{
base.OnStopped();
}
}
}
- SuperSocket 中的命令設計出來是為了處理來自客戶端的請求的, 它在業務邏輯處理之中起到了很重要的作用。所以我們寫一個自己的命令類。(后面好像處理不了,我也不知道怎么回事)
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SuperSocketTest.src.Service.UDPServer
{
//這邊權限要public才能被掃描到,CommandBase的第一個填剛剛自己創建的MySession
public class MyCommand : CommandBase<MySession, StringRequestInfo>
{
public override string Name
{
get
{
//調用命令的名字,如果不覆蓋,默認是類名
return "001";
}
}
public override void ExecuteCommand(MySession session, StringRequestInfo requestInfo)
{
//向客戶端返回信息,已接受到命令
session.Send("Hello,I'm UDP server! The parameter you send is " + requestInfo.Body);
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!--下面configSections這項一定是放在configuration里的第一個,不然會報錯-->
<configSections>
<section name="superSocket"
type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine" />
</configSections>
<superSocket>
<servers>
<!--serverType中,逗號左邊的是你自定義的server在項目中的位置(命名空間加類名),逗號右邊是項目名(命名空間的第一個.之前的),ip就是服務器ip(Any代表本機),port端口號,mode:Tcp或者Udp模式-->
<server name="SSTUDP"
serverType="SuperSocketTest.src.Service.UDPServer.MyServer,SuperSocketTest"
ip="Any" port="2020" mode="Udp">
</server>
</servers>
</superSocket>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
using SuperSocket.SocketBase;
using SuperSocket.SocketEngine;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SuperSocketTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("按任意鍵以啟動服務器!");
Console.ReadKey();
Console.WriteLine();
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();
//關閉服務器
bootstrap.Stop();
Console.WriteLine("服務器已停止!");
Console.ReadKey();
}
}
}
- 結果:

-- 成功,這邊使用的自定義的命令行格式!
2. 方案二:通過代碼的方式啟動,這樣簡單些,但是文檔中沒有給出方法,在查閱源碼后發現,設置啟動模式可以在“AppServer”類的“Setup”方法中設置。
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;
using SuperSocket.SocketBase.Protocol;
using SuperSocket.SocketEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SuperSocketTest
{
class Program
{
/// <summary>
/// 客戶端計數器
/// </summary>
static int clientCount = 0;
static void Main(string[] args)
{
Console.WriteLine("按任意鍵以啟動服務器!");
Console.ReadKey();
Console.WriteLine();
var appServer = new AppServer();
//在這設置服務器模式,更多屬性請參閱官方文檔
if (!appServer.Setup(new ServerConfig
{
Ip = "Any",
Port = 2020,
Mode = SocketMode.Udp
}))//配置服務器
{
Console.WriteLine("配置服務器失敗!");
Console.ReadKey();
return;
}
Console.WriteLine();
//嘗試啟動服務器
if (!appServer.Start())
{
Console.WriteLine("啟動失敗!");
Console.ReadKey();
return;
}
Console.WriteLine("服務器啟動成功,按 ‘q’ 鍵停止服務器!");
//注冊新連接
appServer.NewSessionConnected += new SessionHandler<AppSession>(appServer_NewSessionConnected);
//注冊命令響應
appServer.NewRequestReceived += new RequestHandler<AppSession, StringRequestInfo>(appServer_NewRequestReceived);
while (Console.ReadKey().KeyChar != 'q')
{
Console.WriteLine();
continue;
}
//停止服務器
appServer.Stop();
Console.WriteLine("服務器已停止!");
Console.ReadKey();
}
/// <summary>
/// 處理第一次連接
/// </summary>
/// <param name="session">socket會話</param>
private static void appServer_NewSessionConnected(AppSession session)
{
clientCount++;
session.Send("Hello,you are the " + clientCount + "th connected client!");
}
/// <summary>
/// 處理命令
/// </summary>
/// <param name="session">socket會話</param>
/// <param name="requestInfo">請求的內容,詳見官方文檔</param>
private static void appServer_NewRequestReceived(AppSession session, StringRequestInfo requestInfo)
{
switch (requestInfo.Key.ToUpper())
{
case ("001")://同樣添加一條命令,更多命令的使用請查閱文檔
session.Send("Hello,I'm UDP server! The parameter you send is " + requestInfo.Body);
break;
}
}
}
}
- 結果:

-- 成功!
二、總結
- 可以通過配置和代碼來啟動服務器。
- 代碼在AppServer.Setup函數下配置。
- 文件配置在App.config文件里配置,再通過Bootstrap啟動服務器。
- 對於TCP方式同樣適用,只需要設置mode的值為Tcp即可。
- SuperSocket很棒!怎么三年前沒有發現這個寶藏呢!
- UDP測試 V1軟件:UDP收發器 Gitee
謝謝支持