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
, AppSecret
these 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, wss
the agreement WebSocket
is the only choice.
establish connection
Server
Well, first of all it is to provide network connection services on the server side.
Because websocket
is based http
protocol, so the .Net
inside or use HttpListener
to listen.
After the listener to start running, you can use HttpListener.GetContext
to 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.IsWebSocketRequest
judge this http
connection is not a legitimate WebSocket
connected.
And then HttpListenerContext.AcceptWebSocketAsync
, so you can get one with the client WebSocket
is connected.
For convenience, we are in the service side of GameMonitor
the definition of a project in GameConnection
class, to focus on the user's connection.
We GameServer
add a class inside HttpListener ClientListener
member, 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 ClientListener
and ListenThread
initialized:
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 GameConnection
class mainly includes basic information and a method for receiving connection data. Here we make GameConnection
the 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 GameServer
management 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:
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:
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:
Server:
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