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

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 (IX)

Small micro-channel program is a good platform, used to make cell phone games is really good, simple, versatile, and easy to spread.
- Uncle Mao

Well, now we start doing client, the client selects a small micro-channel program, so we want to download 微信Web开发者工具.
So why plagiarism Tencent will do, once their practice something, does not even have a name, and that if the foreigners do, Paul missing the big names take what it ...... for example TCStadio, TCWARESHOP like a look that tall on.

Well, China is a low-key people, in short, if you have not installed quickly install it.

Applet application process is very simple, go their own micro-channel public platform to check, I was not here long-winded.

Remember that your focus is AppID, AppSecretthese two things.

The client then the first thing to do, and that is to establish a network connection to the server, according to a document given by the company Tencent, wssthe agreement WebSocketis the only choice.

establish connection

Server

Well, first of all it is to provide network connection services on the server side.
Because websocketis based httpprotocol, so the .Netinside or use HttpListenerto listen.
After the listener to start running, you can use HttpListener.GetContextto accept the connection client, this is a synchronous method blocks the current thread until the user connects up so far.

Client connection is up, you can HttpListenerContext.Request.IsWebSocketRequestjudge this httpconnection is not a legitimate WebSocketconnected.

And then HttpListenerContext.AcceptWebSocketAsync, so you can get one with the client WebSocketis connected.

For convenience, we are in the service side of GameMonitorthe definition of a project in GameConnectionclass, to focus on the user's connection.

We GameServeradd a class inside HttpListener ClientListenermember, it would have on his live to dry ~!
Because listeners will block the main thread, it should also have a listening thread ListenThread.
Also you need a record of the connection pool ConnectionPool, so help us manage the current all connected.
The method of construction of the inside ClientListenerand ListenThreadinitialized:

private HttpListener ClientListener;
private Thread ListenThread;
public List<GameConnection> ConnectionPool = new List<GameConnection>(1000);
……
public GameServer(MainForm monitor)
        {
            Status = 0;
            Monitor = monitor;
            LOG("GameServer创建成功");
            gGame = new Game(LOG);

            ClientListener = new HttpListener();
            ClientListener.Prefixes.Clear();
            ClientListener.Prefixes.Add("http://localhost:666/");
            ListenThread = new Thread(new ThreadStart(Listen));
        }
……
private void Listen()
        {
            ClientListener.Start();
            while (ClientListener.IsListening)
            {
                try
                {
                    HttpListenerContext context = ClientListener.GetContext();
                    HttpListenerRequest request = context.Request;
                    LOG("收到请求来自:" + request.UserHostAddress + " 的请求");
                    if (request.IsWebSocketRequest)
                    {
                        Task<HttpListenerWebSocketContext> ret = context.AcceptWebSocketAsync(null);
                        ret.Wait();
                        if (ret.Result.WebSocket != null)
                        {
                            if (ConnectionPool.Count < ConnectionPool.Capacity)
                            {
                                GameConnection connection = new GameConnection(request.UserHostAddress, ret.Result.WebSocket, LOG);
                            }
                            else
                            {
                                ret.Result.WebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "{\"result\":\"fail\",\"msg\":\"连接已满\"}", CancellationToken.None);
                            }
                        }
                    }
                    else
                    {
                        HttpListenerResponse response = context.Response;
                        response.Close();
                    }

                }
                catch (Exception e)
                {
                    LOG(e.Message);
                }
            }
        }

The GameConnectionclass mainly includes basic information and a method for receiving connection data. Here we make GameConnectionthe connection to send a "How are you?" To the client. Then began asynchronous receive information sent by the client, after receiving LOG out.

class GameConnection
    {
        public string IP;
        public WebSocket mSocket;
        private Action<string> LOG;

        public GameConnection(string IP,WebSocket mSocket, Action<string> LOGFUN = null)
        {
            this.IP = IP;
            this.mSocket = mSocket;
            LOG = LOGFUN==null? x => { }:LOGFUN;
            LOG("来自 "+IP+" 连接建立成功");
            ArraySegment<byte> segment = new ArraySegment<byte>(Encoding.UTF8.GetBytes("How are you?"));
            mSocket.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None);
            ReceiveDataAsync();
        }

        private async void ReceiveDataAsync()
        {
            while (mSocket.State == WebSocketState.Open)
            {
                WebSocketReceiveResult result;
                try
                {
                    ArraySegment<byte> receivebuff = new ArraySegment<byte>(new byte[1024]);
                    result = await mSocket.ReceiveAsync(receivebuff, CancellationToken.None);
                    string receiveStr = Encoding.UTF8.GetString(receivebuff.ToArray(), 0, result.Count);
                    LOG("收到来自 " + IP + " 的信息:" + receiveStr);

                }
                catch
                {
                    LOG("连接强行中断");
                    await mSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "{\"result\":\"fail\",\"msg\":\"服务器断开\"}", CancellationToken.None);
                }
            }
            LOG("连接已断开");
        }
    }

In the GameServermanagement class listening thread start and stop method:

public void StartUp()
        {
            if (Status == 0)
            {
                gGame.Run();
                Status = 1;
                ListenThread.Start();
                LOG("GameServer启动成功");
            }
            else
            {
                LOG("GameServer当前处于启动状态,请勿重复启动");
            }
        }
        public void ShutDown()
        {
            if (Status == 1)
            {
                ClientListener.Stop();
                gGame.Stop();
                Status = 0;                
                LOG("GameServer停机成功");
            }
            else
            {
                LOG("GameServer当前处于停机状态,无需再次停机");
            }
        }

Well, everything is ready, waiting for client connections come up.

Client

Start micro-channel web developer tools to create a new game already registered, fill AppID, path, name, and developer tools for you automatically build a "planes" game template ...... play to see if you can get How many points. Then all files are deleted, encountered can not delete a folder on the restart and then quit deleted. Finally, only three files:
Here Insert Picture Description
then open game.js file, delete everything.
The script file is a small game micro-channel enabled by default, so we can use it to debug what our internet access.
Game.js enter the code in the file:

wx.connectSocket({
  url: 'ws://localhost:666/',
  method: "GET",
  success(res){
    console.log("Socket successed:")
    console.log(res)
    wx.onSocketOpen(
      (res) => {
        console.log("Socket opened:")
        console.log(res)
      }
    )
    wx.onSocketClose(
      (res) => {
        console.log("Socket closed:")
        console.log(res)
      }
    )
    wx.onSocketError((res) => {
      console.log("Socket error:")
      console.log(res)
    })
    wx.onSocketMessage((res)=>{
      console.log("got message:")
      console.log(res)
      wx.sendSocketMessage(
        {
          data:"Fine!Thank you,and you?",
          success:(res)=>{
            console.log("send msg:")
            console.log(res)
          }
        }
      );
    })
  },
  fail(res){
    console.log("Socket failed:")
    console.log(res)
  }
})

Note, be sure to check this:
Here Insert Picture Description
Then, let's run the server side, start GameServer
and then micro-channel web development tools inside, press Ctrl+ B, development tools automatically compile and run this script in the simulator.

Results are as follows:
Client:
Here Insert Picture Description
Server:
Here Insert Picture Description
My god - they communicate very smooth ah!

The basic channels of communication have been transferred through the next step, we are going to achieve real and meaningful instruction issued transfer the data.

Previous: C # server WeChat games - multiplayer online role-playing (eight)
Next: C # server WeChat games - multiplayer online role-playing (X)

See the demo game results with micro-channel scan

Entrance demo

Guess you like

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