Photon Server與Unity3D的交互分為3篇博文實現
(3)Photon Server與Unity3D客戶端的交互
Photon Server是一款實時的Socket服務器和開發框架,快速、使用方便、容易擴展,服務端架構在Windows系統平台上,采用C#語言編寫,Photon Server發布包括兩個部分,Client SDK Release和Server SDK Update,Server SDK的版本是v2.4.5,而Client SDK的版本是v6.2.0。客戶端SDK提供了多種平台的開發API,包括DotNet,Unity3D,C/C++等。SDK就是指可以為第三方開發者提供特定的軟件包、軟件框架、硬件平台、操作系統等創建應用軟件開發工具的集合,並且SDK還能簡單的為某個程序設計語言提供應用程序接口API的一些文件。
PhotonServer官網:https://www.photonengine.com/en/OnPremise。幫助文檔:官網Documentatain右邊的Tutorials、Reference和\Photon-OnPremise-Server-SDK_v4-0-29-11263\doc
1.下載Server SDK(On-Premises)
進入官網,點擊頁面右上角的SDKs,然后在Choose for your project的條件中選中Server,可以看到圖標,點擊圖標后點Download SDK下載exe文件。運行或右鍵解壓服務器端,不要出現中文目錄,解壓出\ Photon-OnPremise-Server-SDK_v4-0-29-11263。
\deploy:部署服務器應用,放置開發服務器的代碼及相關文件(\deploy\bin_Win64\PhotonControl.exe:服務器程序運行文件,證書存放的在\deploy\bin_Win64)
\doc:存放幫助文檔
\lib:存放動態鏈接庫(Photon3Unity3D.dll是用來開發基於Unity3D的客戶端,ExitGamesLibs.dll、Photon.SocketServer.dll、PhotonHostRuntimeInterfaces.dll是用來開發服務器端)
\src-server:提供一些項目的源碼
2. 配置server端的PhotonServer.config文件
打開deploy\bin_Win64\PhotonServer.config。一個Photon instance代表一類配置,一個Photon instance可以包含多個服務器端的應用。
<MMoInstance <!--這個Photon instances的名稱--> MaxMessageSize="512000" MaxQueuedDataPerPeer="512000" PerPeerMaxReliableDataInTransit="51200" PerPeerTransmitRateLimitKBSec="256" PerPeerTransmitRatePeriodMilliseconds="200" MinimumTimeout="5000" MaximumTimeout="30000" DisplayName="MMO" <!--顯示在Photon instances的名稱--> > <!-- 0.0.0.0 opens listeners on all available IPs. Machines with multiple IPs should define the correct one here. --> <!-- Port 5055 is Photon's default for UDP connections. --> <UDPListeners> <UDPListener IPAddress="0.0.0.0" Port="5055" OverrideApplication="Minecraft">"<!--指明這個端口號是給哪個Application使用的--> </UDPListener> </UDPListeners> <!-- 0.0.0.0 opens listeners on all available IPs. Machines with multiple IPs should define the correct one here. --> <!-- Port 4530 is Photon's default for TCP connecttions. --> <!-- A Policy application is defined in case that policy requests are sent to this listener (known bug of some some flash clients) --> <TCPListeners> <TCPListener IPAddress="0.0.0.0" Port="4530" PolicyFile="Policy\assets\socket-policy.xml" InactivityTimeout="10000" OverrideApplication="Minecraft" > </TCPListener> </TCPListeners> <!-- Policy request listener for Unity and Flash (port 843) and Silverlight (port 943) --> <PolicyFileListeners> <!-- multiple Listeners allowed for different ports --> <PolicyFileListener IPAddress="0.0.0.0" Port="843" PolicyFile="Policy\assets\socket-policy.xml" InactivityTimeout="10000"> </PolicyFileListener> <PolicyFileListener IPAddress="0.0.0.0" Port="943" PolicyFile="Policy\assets\socket-policy-silverlight.xml" InactivityTimeout="10000"> </PolicyFileListener> </PolicyFileListeners> <!-- WebSocket (and Flash-Fallback) compatible listener --> <WebSocketListeners> <WebSocketListener IPAddress="0.0.0.0" Port="9090" DisableNagle="true" InactivityTimeout="10000" OverrideApplication="Minecraft"> </WebSocketListener> </WebSocketListeners> <!-- Defines the Photon Runtime Assembly to use. --> <Runtime Assembly="PhotonHostRuntime, Culture=neutral" Type="PhotonHostRuntime.PhotonDomainManager" UnhandledExceptionPolicy="Ignore"> </Runtime> <!-- Defines which applications are loaded on start and which of them is used by default. Make sure the default application is defined. --> <!-- Application-folders must be located in the same folder as the bin_win32 folders. The BaseDirectory must include a "bin" folder. --> <Applications Default="Minecraft"><!--客戶端連接服務器未指定Application時連接默認的Application-->
<!-- MMO Demo Application --> <Application Name="Minecraft"<!--應用名稱--> BaseDirectory="MinecraftServer"<!--\deploy下這個服務器應用的文件名稱--> Assembly="MinecraftServer"<!-—程序集名稱--> Type="MinecraftServer.MinecraftServer"<!--主類名稱--> ForceAutoRestart="true"<!--是否自動重啟--> WatchFiles="dll;config" ExcludeFiles="log4net.config"> </Application> <!-- CounterPublisher Application --> <Application Name="CounterPublisher" BaseDirectory="CounterPublisher" Assembly="CounterPublisher" Type="Photon.CounterPublisher.Application" ForceAutoRestart="true" WatchFiles="dll;config" ExcludeFiles="log4net.config"> </Application> </Applications> </MMoInstance>
3.創建server端類庫
(1)創建類庫:文件-新建-項目-類庫,創建類庫MinecraftServer
(2)創建Application文件夾:在\deploy下創建文件夾MinecraftServer(與配置文件PhotonServer.config里Application中的BaseDirectory對應),然后在Minecraft下創建文件夾bin
(3)設置dll文件生成路徑:右鍵項目-屬性-生成-輸出路徑,設置為\deploy\MinecraftServer\bin
(4)修改程序集名稱跟默認命名空間:右鍵項目-屬性-應用程序,都設置為MinecraftServer(與配置文件PhotonServer.config里Application中的Assembly對應)。
(5)生成dll文件:右鍵項目-生成。以后每次修改都要重新生成。
4.添加server端動態鏈接庫
在\lib里,將ExitGamesLibs.dll、Photon.SocketServer.dll、PhotonHostRuntimeInterfaces.dll 添加到類庫引用
5.創建Server端主類與客戶端連接類
主類命名用項目名稱MinecraftServer並繼承ApplicationBase,該類為服務器端程序入口。
using Photon.SocketServer; namespace MinecraftServer { //所有的server端主類都要繼承自Application public class MinecraftServer: ApplicationBase {
//server端啟動的時候調用,作初始化
protected override void Setup()
{
}
//當一個客戶端請求連接時調用,我們使用一個PeerBase表示Server端和一個客戶端的連接,用來管理server端與客戶端請求的發送與接收 protected override PeerBase CreatePeer(InitRequest initRequest) {
return new ClientPeer(initRequest);//ClientPeer繼承自PeerBase,InitRequest包含連接請求的各種參數。new出來后PhotonServer會幫我們管理ClientPeer。 } //server端關閉的時候調用 protected override void TearDown() {
} } }
客戶端連接類ClientPeer繼承PeerBase,每一個客戶端連接進來都會創建一個ClientPeer,用來管理server端與客戶端請求的發送與接收
using Photon.SocketServer;
using PhotonHostRuntimeInterfaces;
namespace MinecraftServer { //每一個客戶端連接進來都會創建一個ClientPeer public class ClientPeer : Photon.SocketServer.ClientPeer {
public ClientPeer(InitRequest initRequest):base(initRequest)
{
}
//處理客戶端斷開連接的后續工作 protected override void OnDisconnect(DisconnectReason reasonCode, string reasonDetail) { } //處理客戶端的請求 protected override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters) { } } }
6.配置日志
(1)添加動態鏈接庫log4net.dll(log4net是做日志輸出的插件)和ExitGames.Logging.Log4Net.dll(Photon提供用來連接Photon與log4net)。右鍵引用-添加引用-瀏覽,在\lib里。
(2)配置log4net.config。參考\src-server\Mmo\Photon.MmoDemo.Server\log4net.config。詳細學習推薦上官網http://logging.apache.org/log4net或博客園。
<?xml version="1.0" encoding="utf-8" ?> <log4net debug="false" update="Overwrite"> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <file type="log4net.Util.PatternString" value="%property{Photon:ApplicationLogPath}\\Minecraft.Server.log" /><!--value表示日志文件所在的完整路徑,property{Photon:ApplicationLogPath}是根目錄在MyGameServer.cs里配置,Minecraft.Server.log日志的名稱 --> <appendToFile value="true" /> <maximumFileSize value="5000KB" /> <maxSizeRollBackups value="2" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%d [%t] %-5p %c - %m%n" /> </layout> </appender> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <levelMin value="DEBUG" /> <levelMax value="FATAL" /> </filter> </appender> <!-- logger --> <root> <level value="INFO" /> <!--<appender-ref ref="ConsoleAppender" />--> <appender-ref ref="RollingFileAppender" /> </root> <logger name="OperationData"> <level value="INFO" /> </logger> </log4net> <!--這個文檔的復制到輸出目錄要選擇始終復制 -->
(3)日志初始化
using Photon.SocketServer; using ExitGames.Logging; using ExitGames.Logging.Log4Net; using System.IO; using log4net.Config; namespace MinecraftServer { //所有的server端主類都要繼承自Application public class MinecraftServer: ApplicationBase {
//需using ExitGames.Logging;log用來做日志輸出
public static readonly ILogger log = LogManager.GetCurrentClassLogger();
//server端啟動的時候調用,作初始化 protected override void Setup() { //日志的初始化 //this.ApplicationRootPath獲取photonServer應用的根目錄(D:\Photon-OnPremise-Server-SDK_v4-0-29-11263\deploy) log4net.GlobalContext.Properties["Photon:ApplicationLogPath"] = Path.Combine(Path.Combine(this.ApplicationRootPath, "bin_Win64"), "log"); //Path.Combine() 會屏蔽平台的差異。this.BinaryPath獲取輸出路徑(D:\Photon-OnPremise-Server-SDK_v4-0-29-11263\deploy\MyGameServer\bin) FileInfo configFileInfo = new FileInfo(Path.Combine(this.BinaryPath, "log4net.config"));//需using System.IO; if(configFileInfo.Exists) { LogManager.SetLoggerFactory(Log4NetLoggerFactory.Instance);//讓photon知道使用的是Log4Net的日志插件。需using ExitGames.Logging.Log4Net; XmlConfigurator.ConfigureAndWatch(configFileInfo);//讓log4net這個插件讀取配置文件。需using log4net.Config; } //日志輸出 log.Info("服務器應用啟動成功!"); } //當一個客戶端請求連接時調用,我們使用一個PeerBase表示Server端和一個客戶端的連接,用來管理server端與客戶端請求的發送與接收 protected override PeerBase CreatePeer(InitRequest initRequest) { log.Info("一個客戶端應用連接進來!"); return new ClientPeer(initRequest);//ClientPeer繼承自PeerBase,InitRequest包含連接請求的各種參數 }
//server端關閉的時候調用 protected override void TearDown() { log.Info("服務器應用關閉!"); } } }
MinecraftServer.log.Info輸出Info類信息,MinecraftServer.log.Debug輸出Debug類信息,MinecraftServer.log.Error輸出Error類信息等為日志的輸出做分類。
一個應用有3個日志文件:Photon.CLR(輸出應用的配置信息跟Listeners的信息)、Photon-MMoInstance-20180212.log(MMoInstance模塊應用啟動順序的輸出)、Minecraft.Server.log(自定義的輸出)。