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>
  • 最后,主程序中调用Bootstrap启动服务器。
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

谢谢支持

【C#】SuperSocket配置启动UDP服务器的更多相关文章

  1. udp服务器监听(多线程)

    项目一:udp1111 监听的有三个文件分别为: guiHello.java 有关界面和事件响应功能 UdpFunc.java是udp类的封装:发送和接收 udpServer.java是入口函数,无实 ...

  2. C#SuperSocket的搭建--通过配置启动

    之前我们借助一个SuperSocket实现了一个简易版的服务器, 但是不管是Server还是Session都是使用框架的,本篇博客我们要实现自己的Server和Session,来重写框架原生的Serv ...

  3. 转:配置nodemanager启动weblogic服务器

    下面仅供参考,里面表格还有文件目录我是写的linux,刚刚看到原作者是windows, 后面我会把自己配置nodemanager的经过记录上来,我搞得是linux. (一)通过nodemanager本 ...

  4. 04_Weblogic之受管服务器:配置受管服务器,启动受管服务器,解决因为强制关闭Weblogic之后导致启动有问题的问题,配置boot.properties

     配置受管服务器, 先启动WebLogic服务器,启动方式如下: 在WebLogic控制台中的"开发模式"---"锁定并编辑"模式下,点击"Ser ...

  5. Linux的DNS配置2-主从服务器

    1.实验背景 之前写了Linux的DNS配置1-DNS入门,其中只用了一台DNS服务器,但一般在大型网络中,都要通过配置辅助DNS服务器可以提高DNS服务的可靠性,本次实验即配置DNS主从服务器 2. ...

  6. 在 RHEL/CentOS 7 上配置NTP时间服务器

    一.NTP简介 网络时间协议 - NTP - 是运行在传输层 123 号端口的 UDP 协议,它允许计算机通过网络同步准确时间.随着时间的流逝,计算机内部时间会出现漂移,这会导致时间不一致问题,尤其是 ...

  7. netty学习:UDP服务器与Spring整合(2)

    上一篇文章中,介绍了netty实现UDP服务器的栗子. 本文将会对UDP服务器与spring boot整合起来,并使用RedisTemplate的操作类访问Redis和使用Spring DATA JP ...

  8. nacos 1.4.2 建立集群,公司启动linux服务器常用命令

    2022-7-29 编写micro自动处理脚本,并加入了守护精灵进程 先启动prop1 服务器(xx.1xx.165.186) 再启动prop2服务器 (xx.1xx.174.173) ####### ...

  9. Linux系统安装配置NTP时间服务器

    背景 局域网不能上外网情况下同步集群时间,搭建NTP服务器,并设置其他主机每小时同步时间(假设使用地址为192.168.3.21的主机作为NTP服务器) 安装NTP $ sudo yum instal ...

  10. 【实验 1-2】编写一个简单的 UDP 服务器和 UDPP 客户端程序。程序均为控制台程序窗口。

    1.服务器 #include<winsock2.h> //包含头文件#include<stdio.h>#include<windows.h>#pragma comm ...

随机推荐

  1. biancheng-Maven依赖

    目录http://c.biancheng.net/maven2/profile.html 1Maven简介2Maven安装与配置3Maven POM4创建Maven项目5Maven项目的构建与测试6M ...

  2. DCT实现水印嵌入与提取(带攻击)

    问题: 想要用DCT技术,在Matlib上实现水印的隐藏和提取(带GUI界面),且加上一些攻击(噪声.旋转.裁剪),以及用NC值评判! 流程 选择载体 [filename,pathname]=uige ...

  3. 面试题:区分List中remove(int index)和remove(Object obj)

    面试题:区分List中remove(int index)和remove(Object obj) package com.atguigu.exer;import org.junit.Test;impor ...

  4. MapStruct入门使用

    MapStruct入门使用案例 以下是常用的使用举例,按照需求改动即可 @Data public class UserDO{ private int age; private String name; ...

  5. 2024年度Graph+AI开源探索思考

    前记 这篇年度总结其实酝酿了许久,却因诸多原因拖至腊月底,此时赶在春节前发出来,也不失为"农历版"年度总结了.所谓年度总结,一般是"温故而知新",我不太想落入堆 ...

  6. Oracle trunc的使用

    在生产环境中我们经常会用到只取年月日或者时间处理的场景,大多数人用的都是to_char(string,'yyyy-mm-dd')或者to_date(string,'yyyy-mm-dd')来处理,不说 ...

  7. 一种基于Nginx的热点数据调度处理方法

    本文分享自天翼云开发者社区<一种基于Nginx的热点数据调度处理方法>,作者:康****彬 一.应用场景 基于Nginx的热点数据调度处理,热点节点数据负载均衡处理,减少热点节点压力,提高 ...

  8. 导出数据EPPlus

    前言 导出数据在管理系统中经常要用到,目前的Excel导出工具多种多样,如:NPOI.EPPlus等--本篇使用的是EPPlus,记录下在工作中用到的导入导出类,以便后面使用 代码 导出 public ...

  9. autMan奥特曼机器人-对插件权限的管理

    为了避免某些插件在用户不知情的情况下读取使用用户隐私数据,受" 安卓手机上安装的应用需申请电话.位置.通讯录等权限 "的启发,autMan增加了数据桶读取权限设置页面. 当前受限制 ...

  10. 从文件到块: 提高 Hugging Face 存储效率

    Hugging Face 在 Git LFS 仓库 中存储了超过 30 PB 的模型.数据集和 Spaces.由于 Git 在文件级别进行存储和版本控制,任何文件的修改都需要重新上传整个文件.这在 H ...