Giter VIP home page Giter VIP logo

unitysocket_c-s_model's Introduction

Unity3D的C/S架构消息通讯模板

在Unity3D中使用的Socket消息通讯模板,服务器也是Csharp写的。

客户端作为Unity3D项目的一部分,导入到Unity3D工程中,使用某个脚本的Update()方法进行驱动;

服务器是一个单独的控制台程序,需要写一个Main方法。

网络消息MsgXXX

本通讯模型通过一种叫做 “消息协议” 的对象进行通讯。

消息协议通过继承自类MsgBase来定义,本质上是一个具有特定功能的结构。

消息协议的基类:MsgBase类,完成了对所有协议的一些通用操作,编码解码之类的操作,不要修改。

这些消息协议对象中应该包含有此消息协议应有的一些信息,比如登录协议MsgLogin就应该至少包含useridpwd两个字段(成员变量)。

实际上,继承自MsgBase后的自定义消息协议类,看起来就像是C++里的结构体一样,只有构造函数和数个公有成员变量。

自定义新的协议

写新的自定义协议时,只需要且必须继承自MsgBase后在构造函数中为protoName属性赋值为此协议的类名的字符串。

写新的自定义协议时,请保证服务端和客户端都添加了一模一样的新的自定义协议的类声明。

服务端需要同时在类MsgHandler中添加与此协议同名的静态方法,用于处理在收到此协议时所要做的事情。

客户端只需要使用NetManager.AddMsgListener()方法,来动态地监听某一消息的到来并进行对应的处理。

详细方式请分别参考目录ServerClient中的README.md文件。

为什么服务端中消息协议的类型名,消息协议的protoName变量的值,和收到此消息时的处理方法需要同名?

MsgHandler中用来处理收到某消息时的静态方法,会在服务器收到并解析一条消息协议时,通过Csharp的反射机制,使用此收到的消息协议中的成员变量protoName来找到对应的处理方法。

哦对了,客户端虽然不需要写同名的静态回调方法,但是protoName变量也应该是同名的,这个服务端和客户端没差。(简单来说就是对消息协议的类定义应该双端相同)

unitysocket_c-s_model's People

Contributors

hittefield avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.