C # server WeChat games - multiplayer online role-playing (c)

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

C # server WeChat games - multiplayer online role-playing (c)

Those seem very complicated things, often can be broken down into simple small elements. Learn to simplify, which is the basic quality of the program ape.
- Uncle Mao

Previous inside, we mentioned several parts of the server:
Game - Game class
GameWorld - world class
GameServer - gaming service class
GameMonitor - server control interface
AdminWeb - remote control interface

Establish engineering

We start GameMonitorthis section to start, because this part is to control the interface, and then start from here, follow-up work can easily rendering, it makes debugging more efficient.

So, we first create an empty program by VS ( Solution), then add the first project ( project), select the project type Windows Forms App (.NET Framework), project name GameMonitor.

GameMonitor

VS creates a default form for us, the name is Form1, we have renamed this form MainForm, the system prompts whether to change the reference, select Yes.

Then Solution Explorerlocate and double-click in the MainForm.csopen form design interface.
In the Form Designer interface in the properties dialog box of the form Textwas changed to " 游戏监控器." Then drag from a toolbar Buttonto the top left corner of the form,

Check this Button, the Properties dialog box in the Textproperty to " 启动", the Nameproperty is set BTN_Start. This button is used to start and stop our game service.

Then from the inside and then drag a toolbar TextBoxto BTN_Startbelow, will be Nameset TXB_Log, Mutilineset true, Fontset Microsoft YaHei, 15.75pt. I have bad eyes, larger than the font settings, of course, you like you can also set a different font, looked clear and easy enough.

To TXB_Logthe ScrollBarsset Vertical, when such information is more convenient to scroll up and down. Then widened to fill the entire form, and then Anchorset Top, Bottom, Left, Right, so that it can zoom in with the form.

The text box will be used to show the situation after our code to run.

The last effect is as follows:
Form effect

Right-click on a form select View Code ( View Code) can open the code editor window, where we want to manually MainFormform class to add a method to display log information AddLog. code show as below:

private void AddLog(string msg)
        {
            if (msg != null && msg.Length < 1024 && !msg.Trim(' ').Equals(""))//每次显示的信息不能为空也不能太长
            {
                TXB_Log.Text += "[" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:ffff") + "] " + msg + Environment.NewLine;
                while (TXB_Log.Text.Length>30000)//总的显示字符太长的话,就裁掉一些
                {
                    TXB_Log.Text=TXB_Log.Text.Remove(0, 1024);
                }
                //随时滚动到最下面,方便查看
                TXB_Log.Select(TXB_Log.Text.Length,0);
                TXB_Log.ScrollToCaret();
            }
        }

We can in MainFormthe Loadevent handler inside with words of welcome to open the code window in the Form Designer window, double-click interface, the VS automatically added MainForm_Loadinside method plus

AddLog("欢迎!");

However, this method can only be called from within the UI thread, other threads can not use ......
so it should be easy to add to it other agents calling thread.

To the form MainFormclass to add two lines of code:

public delegate void AddLog_Method(string msg);//定义一个代理类型
public AddLog_Method Delegate_AddLog;//创建一个已定义代理类型的代理对象

In the Form MainFormclass constructor, the proxy object will Delegate_AddLogpoint to our AddLogmethod:

public MainForm()
        {
            InitializeComponent();
            Delegate_AddLog = AddLog;//将代理对象指向方法
        }

Then, we can use anywhere Invoketo call it.

Invoke(Delegate_AddLog, new object[] { "你好"});

We put this statement on the BTN_Startinside to test ...... double-click in the Form Designer window BTN_Start, VS will automatically click event handler method to add us. We just need to write code directly on it.

private void BTN_Start_Click(object sender, EventArgs e)
        {            
            AddLog("来自UI线程");
            Task.Run(
                new Action(
                () =>
                {
                    try
                    {
                        Invoke(Delegate_AddLog, new object[] { "来自非UI线程" });
                    }
                    catch{ }
                }
                )
                );
        }

Debugging effects:Debugging effect

In this way, a simple monitoring form to get, the next step can begin to consider the GameServer.

GameServer

In the Solution Explorerwindow, select the GameMonitorproject, right click select Add -> class, add a name for GameServerthe category.
Then add a private member for the class

private readonly MainForm Monitor;

This is a monitoring form reference.
Then move the cursor to the class name, press alt+ enterbring up the shortcut menu, select Generate constractorand click OK, VS will automatically help us generate constructor.
In the constructor we can create a successful send a log.

public GameServer(MainForm monitor)
        {
            Monitor = monitor;
            try
            {
                Monitor.Invoke(Monitor.Delegate_AddLog, new object[] { "GameServer创建成功" });
            }
            catch{ }
        }

Back to MainFormclass, the BTN_Startcorresponding content instead create a game server function:

private void BTN_Start_Click(object sender, EventArgs e)
        {
            AddLog("启动");
            GameServer server = new GameServer(this);
        }

Debug it, click on the 启动button as usual -
Debugging effect
we put this serverinto clicking a function in response to the outside, as MainFormmembers. Then let it in MainFormthe MainForm_Loadinstantiated, which would allow MainFormother methods to manipulate the.

We give GameServeradd a class member state flag Statusand three methods LOG, StartUpand ShutDownto indicate the status and display the log, control start and stop.

class GameServer
    {
        private readonly MainForm Monitor;
        public int Status;
        public GameServer(MainForm monitor)
        {
            Status=0;
            Monitor = monitor;
            LOG("GameServer创建成功");
        }
        private void LOG(string msg)
        {
            try
            {
                Monitor.Invoke(Monitor.Delegate_AddLog, new object[] { msg });
            }
            catch{ }
        }
        public void StartUp()
        {
          if (Status == 0)
            {
                Status = 1;
                LOG("GameServer启动成功");
            }
            else
            {
                LOG("GameServer当前处于启动状态,请勿重复启动");
            }
        } 
        public void ShutDown()
        {
          if (Status == 1)
            {
                Status = 0;
                LOG("GameServer停机成功");
            }
            else
            {
                LOG("GameServer当前处于停机状态,无需再次停机");
            }
         } 
    }

Then the MainFormclass inside BTN_Startthe respective function contents changed

private void BTN_Start_Click(object sender, EventArgs e)
        {
            if (server.Status == 0)
                server.StartUp();
            else
                server.ShutDown();
        }

Then BTN_Startthe Textchange 启动/停止
debug it:
Debugging effect
ah ...... very good thing ......

This is a write here, mainly to build a server-side framework, the next, we have to in-depth discussion of the operating mechanism GameServer.

Previous: C # server WeChat games - multiplayer online role-playing (two)
Next: C # server WeChat games - multiplayer online role-playing (d)

See the demo game results with micro-channel scan

Entrance demo

Guess you like

Origin blog.csdn.net/foomow/article/details/92080582