您的位置:首页 > 博客中心 > 数据库 >

SuperSocket框架学习笔记4-SuperWebSocket---使用SubCommandBase

时间:2022-03-10 17:22

首先下载所需要的 DLL

http://download.csdn.net/detail/wai2dance123/7389285

 

或者参见第2章  到SuperSocket官网下载

http://www.cnblogs.com/xmcrew/p/3747354.html

 

 

1,新建一个 .NET4.0 控制台应用程序 命名为 DiyServers

添加以下引用

gxlsystem.com,布布扣

 

将默认的Program.cs改名为  DiyServers.cs

 

并添加以下命名空间

gxlsystem.com,布布扣

 

 

2,写自己的DSession和DServer继承自 《 WebSocketSession  和 WebSocketServer 》

新建两个class文件 分别命名   DSession和DServer

并都 添加以下命名空间

gxlsystem.com,布布扣

 

 

首先在 DSession中 添加 父类继承

public class DSession : WebSocketSession<DSession>

再添加以下代码

gxlsystem.com,布布扣gxlsystem.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;



using SuperWebSocket.SubProtocol;
using System.Reflection;
using SuperWebSocket;
using SuperSocket.SocketBase;
namespace DiyServer
{
    public class DSession : WebSocketSession<DSession>
   {

       public string Name { get; private set; }

       protected override void OnSessionStarted()
       {
           //Read name from path
           var name = Path;

           if (string.IsNullOrEmpty(name))
               name = "Anoy";
           else
               name = Path.TrimStart(‘/‘);

           Name = name;
           Console.WriteLine("有新用户连接到服务器了"+ this.SessionID);
           this.Send("Welcome to DiySuperWebSocket");
       }

       

       protected override void OnSessionClosed(CloseReason reason)
       {
           Console.WriteLine("客户端断开了连接");
           //add your business operations
       }

    }
}
View Code gxlsystem.com,布布扣gxlsystem.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SuperWebSocket.SubProtocol;
using System.Reflection;
using SuperWebSocket;
namespace DiyServer
{
    public class DServer : WebSocketServer<DSession>
    {
        public DServer()
        { 
            
        }

        

    }
}
View Code gxlsystem.com,布布扣gxlsystem.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using SuperWebSocket.SubProtocol;

namespace DiyServer
{
    public class ADD : SubCommandBase<DSession>
    {
        public override void ExecuteCommand(DSession session, SubRequestInfo requestInfo)
        {
            var paramArray = requestInfo.Body.Split(‘#‘);

            session.Send(
                "ADD 返回数值Function Bakc:" +  
                ( 
                int.Parse(  paramArray[0].ToString()  ) 
                + 
                int.Parse(  paramArray[1].ToString()  )
                ).ToString()
                );
            Console.WriteLine("GetADDCommand");
            
          

        }
    }
}
View Code gxlsystem.com,布布扣gxlsystem.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using SuperWebSocket.SubProtocol;

namespace DiyServer
{
    public class SUB : SubCommandBase<DSession>
    {
        public override void ExecuteCommand(DSession session, SubRequestInfo requestInfo)
        {
            var paramArray = requestInfo.Body.Split(‘#‘);
           
          
            session.Send("SUB Function Bakc:" + 
                (
                int.Parse(  paramArray[0].ToString() ) 
                - 
                int.Parse(  paramArray[1].ToString() )
                ).ToString()
                );

            Console.WriteLine("GetSUBCommand");

        }
    }
}
View Code gxlsystem.com,布布扣

继续添加

gxlsystem.com,布布扣

 

然后在VS2012中打开这个App.config文件

在server [非servers]节点中 添加以下节点

gxlsystem.com,布布扣

 

其它的节点暂时还不知道具体什么意思,望大家指点,我这里就没有变动,就是添加了

commandAssemblies这个节点

完整 App.config代码如下 :

gxlsystem.com,布布扣gxlsystem.com,布布扣
<?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="SuperWebSocket"
              ip="Any" port="2013">
        <commandAssemblies>
          <add assembly="BasicModules"></add>
        </commandAssemblies>
      </server>
    </servers>
    <serverTypes>
      <add name="SuperWebSocket"
           type="SuperWebSocket.WebSocketServer, SuperWebSocket" />
    </serverTypes>
  </superSocket>
</configuration>
View Code gxlsystem.com,布布扣gxlsystem.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SuperWebSocket;
using SuperWebSocket.SubProtocol;

using System.Reflection;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;


namespace DiyServer
{
    public class DiyServers
    {
       
        static void Main(string[] args)
        {
           

            Console.WriteLine("SuperWebSocket.DiyServer服务器\n 请按一下任意键启动服务器!");

            Console.ReadKey();
            Console.WriteLine();
            //声明自己的WebSocketServer类
            var appServer = new DServer();
           
            var serConfig = new ServerConfig();
            serConfig.Port = 2012;
            //设置编码类型,默认的我试过了,Unity3D无法识别中文
            serConfig.TextEncoding = "GB2312";
            
            //Setup the appServer
            if (!appServer.Setup(serConfig )) //Setup with listening port
            {
                Console.WriteLine("初始化失败!");
                Console.ReadKey();
                return;
            }
                  
            Console.WriteLine();

            //Try to start the appServer
            if (!appServer.Start())
            {
                Console.WriteLine("服务器启动失败!");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("服务器启动成功, 按 ‘q‘ 退出服务器!");

            while (Console.ReadKey().KeyChar != ‘q‘)
            {
                Console.WriteLine("客户端数:"+ appServer.SessionCount );
                Console.ReadKey();
                continue;
            }

            //停止服务器 the appServer
            appServer.Stop();

            Console.WriteLine();
            Console.WriteLine("The server was stopped!");
            Console.ReadKey();


        }




    }
}
View Code gxlsystem.com,布布扣

 

 

 客户端 完整代码如下

注意Unity3D类名需要和文件名完全一致,并且不得使用中文路径,请注意

sSCilents.cs

gxlsystem.com,布布扣gxlsystem.com,布布扣
using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.Net;
using SuperSocket.ClientEngine;

using WebSocket4Net;

using System.Threading;


public class sSCilents : MonoBehaviour {

    
    public WebSocket myClient;
    
    public string Mgs;
    
    Thread UnityThread;
    void Awake()
    {
        
        Mgs ="ServerBackData";
        Application.runInBackground = true;
    }

    
    
    void OnGUI()
    {
       if(GUILayout.Button("Connected") )
       {
            UnityThread = new Thread(new ThreadStart(StatUnityClient ) );
            UnityThread.Start();
            
       }
        
        Mgs = GUI.TextField( new Rect(120,0,200,50), Mgs );
        if(GUILayout.Button("Sends ADD") )
       {
             myClient.Send( "ADD 5#6"  );
            Debug.Log( "Send SUB OK" );
            
       }
        
        
        if(GUILayout.Button("Send SUB") )
       {
           
           myClient.Send( "SUB 26#1"  );
            Debug.Log( "Send SUB OK" );
          
       }
    
    }
    
    
    public void StatUnityClient()
    {
          
            myClient = new  WebSocket( "ws://127.0.0.1:2012");
            myClient.Opened += OnConnectedss;
            
        
            myClient.DataReceived +=OnDataReceivedss;
            myClient.MessageReceived += OnMessageReceivedss;
            myClient.Open();
        
    }
    
    public void OnConnectedss(object sender, EventArgs e )
    {
        
         myClient.Send("Hello World!");

        Debug.Log("NewConnected To Server OKOK");
    }
    
    
    public void OnDataReceivedss(object sender, DataReceivedEventArgs e )
    {
        
        Debug.Log(  Encoding.GetEncoding("gb2312").GetString( e.Data ) );
        
        Mgs = Encoding.GetEncoding("gb2312").GetString( e.Data );
        
         Debug.Log("NewDataRevcei ");
        
            }
    
        
    public void OnMessageReceivedss(object sender, MessageReceivedEventArgs e )
    {
        
        Debug.Log(   e.Message  );
        
    }
    public void OnApplicationQuit()
    {
        
        myClient.Close();
        myClient = null;
        UnityThread.Abort();
        UnityThread = null;
    }
    
}
View Code gxlsystem.com,布布扣

 

再启动Unity3D客户端

gxlsystem.com,布布扣

 

先点击 Connected , 点击左下角

弹出控制台 或者 点击上面的Windows-->Console

gxlsystem.com,布布扣

 

再分别点击 Sends ADD 和 Send SUB按钮

gxlsystem.com,布布扣

 

出现如图 数据,恭喜SuperWebSocket服务器自定义SubCommandBase命令加载器

搭建成功!嘿嘿嘿!

未完,待续......敬请期待

本人C#菜鸟,很多还没有研究透,代码写的渣渣,请勿扔鸡蛋,嘿嘿嘿!

我的小站:http://wai2dance.s1.jutuo.net/

QQ:2360450496

SuperSocket官方QQ群:373076764

欢迎大家来一起研究开发这个Socket框架!

 

 

 

 

 

SuperSocket框架学习笔记4-SuperWebSocket---使用SubCommandBase,布布扣,bubuko.com

热门排行

今日推荐

热门手游