Photon教程——建立簡單的Photon服務器(一)

建立簡單的Photon服務器(一)

上一篇博文(Photon教程——Photon的獲取)的地址:https://blog.csdn.net/ultramansail/article/details/102755749

創建一個新的項目

一、新建項目

1.打開Visual Studio 2019,新建一個類庫

2.命名爲GameServer,VS會幫我們新建一個Class1.cs文件,我們不要管它

3.右擊解決方案資源管理器的“依賴項”,點擊“添加引用”

4.彈出引用管理器窗口,點擊“瀏覽”按鈕,把PhotoHostRuntimeInterface.dll、ExitGames.logging.Log4Net.dll、log4net.dll、photon.SocketSever.dll、ExitGameLibs.dll這幾個文件加進去(注:這幾個dll文件都在Photon根目錄的“lib”的文件夾中

創建Photon服務端代碼

1.右擊解決方案,點擊“添加->新建項”按鈕,選擇類,新建一個類,命名爲GameServer.cs

2.讓GameSever類繼承ApplicationBase類,注意引用ApplicationBase要引入命名空間“Photon.Socket”

 

注:

CreatePeer方法在一個客戶端連接到服務器時調用

Setup方法在服務器初始化(移動成功)時調用

TearDown方法在服務器關閉時調用

3.實現CreatePeer方法

(1)新建一個類,命名爲GamePeer,繼承ClientSever類(注意引入的命名空間),Photon將通過這個類與客戶端通信

(2)構造函數GamePeer

注:

OnDisconnect方法:當客戶端失去連接的時候調用

PnOperationRequest方法:當客戶端向服務器發送請求時調用

(3)實現CreatePeer方法

(4)完整代碼如下

GameServer:

using System;
using System.Collections.Generic;
using System.Text;
using Photon.SocketServer;

namespace GameServer
{
    class GameServer : ApplicationBase
    {
        //當一個客戶端連接到服務器時調用
        protected override PeerBase CreatePeer(InitRequest initRequest)
        {
            return new GamePeer(initRequest);
        }

        //當服務器初始化(移動成功)時調用
        protected override void Setup()
        {
            
        }

        //當服務器關閉時調用
        protected override void TearDown()
        {
            
        }
    }
}


GamePeer:

using System;
using System.Collections.Generic;
using System.Text;
using Photon.SocketServer;
using PhotonHostRuntimeInterfaces;

namespace GameServer
{
    class GamePeer : ClientPeer
    {
        //用這個類來根客戶端進行通信
        public GamePeer(InitRequest request) : base(request)
        {

        }

        //當客戶端失去連接的時候調用
        protected override void OnDisconnect(DisconnectReason reasonCode, string reasonDetail)
        {
            
        }

        //當客戶端向服務器發送請求時調用
        protected override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters)
        {
            
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章