公司需求要了解photon+unity3d的部署與使用,今天開始研究photon。
首先實現登陸服務器功能。
首先去PhotonServer SDK下載服務器端SDK,需要登錄的,就先註冊一個賬號吧.
解壓出來是四個文件
deploy:主要存放photon的服務器控制程序和服務端Demo
doc:顧名思義,文檔
lib:Photon類庫,開發服務端需要引用的
src-server:服務端Demo源代碼
一、配置服務器端
打開deploy文件夾,看到包含了不同平臺編譯出的Photon目錄,以“bin_”爲前綴命名目錄,選擇你的電腦對應的文件夾打開,看到PhotonControl.exe,運行後,可以在windows右下角看到一個圖標,點擊圖標可以看到photon服務器控制菜單,這個以後再做詳細介紹.
打開visual stadio,新建項目,選擇c# 類庫,應用程序名字叫做MyServer.
完成後,把我們的Class1.cs,改名爲MyApplication.cs,作爲服務器端主類.然後在當前項目添加引用,鏈接到剛纔提到的lib文件夾目錄下,添加以下引用:
ExitGamesLibs.dll,Photon.SocketServer.dll,PhotonHostRuntimeInterfaces.dll
然後新建一個類:MyPeer.cs,寫法如下:
using System;
using System.Collections.Generic;
using Photon.SocketServer;
using PhotonHostRuntimeInterfaces;
namespace MyServer
{
using Message;
using System.Collections;
public class MyPeer : PeerBase
{
Hashtable userTable;
public MyPeer(IRpcProtocol protocol,IPhotonPeer photonPeer)
: base(protocol, photonPeer)
{
userTable = new Hashtable();
userTable.Add("user1", "pwd1");
userTable.Add("user2", "pwd2");
userTable.Add("user3", "pwd3");
userTable.Add("user4", "pwd4");
userTable.Add("user5", "pwd5");
}
protected override void OnDisconnect(PhotonHostRuntimeInterfaces.DisconnectReason reasonCode, string reasonDetail)
{
}
protected override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters)
{
switch (operationRequest.OperationCode) {
case (byte)OpCodeEnum.Login:
string uname = (string)operationRequest.Parameters[(byte)OpKeyEnum.UserName];
string pwd = (string)operationRequest.Parameters[(byte)OpKeyEnum.PassWord];
if (userTable.ContainsKey(uname) && userTable[uname].Equals(pwd))//login success
{
SendOperationResponse(new OperationResponse((byte)OpCodeEnum.LoginSuccess, null),new SendParameters());
}
else
{ //login fauled
SendOperationResponse(new OperationResponse((byte)OpCodeEnum.LoginFailed, null), new SendParameters());
}
break;
}
}
}
}
OnOperationRequest方法中驗證用戶名和密碼,然後發送響應給客戶端.需要用到的枚舉一個類如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyServer.Message
{
enum OpCodeEnum : byte
{
//login
Login = 249,
LoginSuccess = 248,
LoginFailed = 247,
//room
Create = 250,
Join = 255,
Leave = 254,
RaiseEvent = 253,
SetProperties = 252,
GetProperties = 251
}
enum OpKeyEnum : byte
{
RoomId = 251,
UserName = 252,
PassWord = 253
}
}
MyApplication.cs類這樣寫:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Photon.SocketServer;
namespace MyServer
{
public class MyApplication : ApplicationBase
{
protected override PeerBase CreatePeer(InitRequest initRequest)
{
return new MyPeer(initRequest.Protocol, initRequest.PhotonPeer);
}
protected override void Setup()
{
}
protected override void TearDown()
{
}
}
}
完成後,在解決方案資源管理器中選中當前項目,打開屬性,選擇生成選項卡,把輸出路徑改成bin\,然後就生成類庫吧
複製當前項目下MyServer文件夾到deploy文件夾下,刪除除了bin文件夾以外其他所有文件和文件夾,然後文本編輯器打開deploy\bin_Win64\PhotonServer.config配置文件(我的是win7 64位機器,就選擇這個),添加以下配置:
<Application
Name="MyServer"
BaseDirectory="MyServer"
Assembly="MyServer"
Type="MyServer.MyApplication"
EnableAutoRestart="true"
WatchFiles="dll;config"
ExcludeFiles="log4net.config">
Name:項目名字
BaseDirectory:根目錄,deploy文件夾下爲基礎目錄
Assembly :是在生成的類庫中的bin目錄下與我們項目名稱相同的.dll文件的名字
Type:是主類的全稱,在這裏是:MyServer.MyApplication,一定要包括命名空間
EnableAutoRestart:是否是自動啓動,表示當我們替換服務器文件時候,不用停止服務器,替換後photon會自動加載文件
WatchFiles和ExcludeFiles
這段代碼放在<Default><Applications>放這裏</Applications></Default>節點下面
完成後保存,運行托盤程序deploy\bin_Win64\PhotonControl.exe,
運行它,如果托盤圖標沒有變灰,說明服務器運行成功。
二、客戶端
首先從官網下載Unity
SDK,打開Unity3d編輯器,首先把Photon-Unity3D_v3-0-1-14_SDK\libs\Release\Photon3Unity3D.dll導入到Unity中。
客戶端過程需要請求服務器並接收服務器的響應下面上代碼,就一個類搞定:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using ExitGames.Client.Photon;
public class TestConnection : MonoBehaviour,IPhotonPeerListener {
public string address;
PhotonPeer peer;
ClientState state = ClientState.DisConnect;
string username = "";
string password = "";
// Use this for initialization
void Start () {
peer = new PhotonPeer(this,ConnectionProtocol.Udp);
}
// Update is called once per frame
void Update () {
peer.Service();
}
public GUISkin skin;
void OnGUI(){
GUI.skin = skin;
switch(state){
case ClientState.DisConnect:
GUI.Label(new Rect(Screen.width/2,Screen.height/2-30,300,40),"click the button to connect.");
if(GUI.Button(new Rect(Screen.width/2,Screen.height/2,100,30),"Connect")){
peer.Connect(address,"MyServer");
state = ClientState.Connecting;
}
break;
case ClientState.Connecting:
GUI.Label(new Rect(Screen.width/2,Screen.height/2-30,300,40),"Connecting to Server...");
break;
case ClientState.Connected:
GUILayout.BeginArea(new Rect((Screen.width-500)/2,(Screen.height-400)/2,500,400));
//
GUILayout.BeginVertical();
GUILayout.Label("Connect Success! Please Login.");
//draw username
GUILayout.BeginHorizontal();
GUILayout.Label("UserName:");
username = GUILayout.TextField(username);
GUILayout.EndVertical();
//draw password
GUILayout.BeginHorizontal();
GUILayout.Label("Password:");
password = GUILayout.TextField(password);
GUILayout.EndVertical();
//draw buttons
GUILayout.BeginHorizontal();
if(GUILayout.Button("login")){
userLogin(username,password);
}
if(GUILayout.Button("canel")){
state = ClientState.DisConnect;
}
GUILayout.EndVertical();
GUILayout.EndVertical();
GUILayout.EndArea();
break;
case ClientState.ConnectFailed:
GUI.Label(new Rect(Screen.width/2,Screen.height/2-30,300,40),"Connect Failed.");
break;
case ClientState.LoginSuccess:
GUILayout.BeginArea(new Rect((Screen.width-500)/2,(Screen.height-400)/2,500,400));
GUILayout.Label("Login Success!");
GUILayout.EndArea();
break;
case ClientState.LoginFailed:
GUILayout.BeginArea(new Rect((Screen.width-500)/2,(Screen.height-400)/2,500,400));
GUILayout.Label("Login Failed!");
GUILayout.EndArea();
break;
}
}
#region My Method
IEnumerator connectFailedHandle(){
yield return new WaitForSeconds(1);
state = ClientState.DisConnect;
}
void userLogin(string uname,string pwd){
Debug.Log("userLogin");
Dictionary<byte,object> param = new Dictionary<byte, object>();
param.Add((byte)OpKeyEnum.UserName,uname);
param.Add((byte)OpKeyEnum.PassWord,pwd);
peer.OpCustom((byte)OpCodeEnum.Login,param,true);
}
IEnumerator loginFailedHandle(){
yield return new WaitForSeconds(1);
Debug.Log("loginFailedHandle");
state = ClientState.Connected;
}
#endregion
#region IPhotonPeerListener implementation
public void DebugReturn (DebugLevel level, string message)
{
}
public void OnOperationResponse (OperationResponse operationResponse)
{
switch(operationResponse.OperationCode)
{
case (byte)OpCodeEnum.LoginSuccess:
Debug.Log("login success!");
state = ClientState.LoginSuccess;
break;
case (byte)OpCodeEnum.LoginFailed:
Debug.Log("login Failed!");
state = ClientState.LoginFailed;
StartCoroutine(loginFailedHandle());
break;
}
}
public void OnStatusChanged (StatusCode statusCode)
{
switch(statusCode){
case StatusCode.Connect:
Debug.Log("Connect Success! Time:"+Time.time);
state = ClientState.Connected;
break;
case StatusCode.Disconnect:
state = ClientState.ConnectFailed;
StartCoroutine(connectFailedHandle());
Debug.Log("Disconnect! Time:"+Time.time);
break;
}
}
public void OnEvent (EventData eventData)
{
}
#endregion
}
public enum ClientState : byte{
DisConnect,
Connecting,
Connected,
ConnectFailed,
LoginSuccess,
LoginFailed
}
public enum OpCodeEnum : byte
{
//login
Login = 249,
LoginSuccess = 248,
LoginFailed = 247,
//room
Create = 250,
Join = 255,
Leave = 254,
RaiseEvent = 253,
SetProperties = 252,
GetProperties = 251
}
public enum OpKeyEnum : byte
{
RoomId = 251,
UserName = 252,
PassWord = 253
}