1. 程式人生 > >搭建unity客戶端

搭建unity客戶端

layout photo tom listener 普通 ngui 客戶端程序 protoc clas

1.新建個unity的項目ChatClient

2.在unityMain Camera下掛載個腳本PhotonServerEngine做為與服務器端通信的腳本

3.PhotonServerEngine腳本中添加引用Photon3Unity3D.dll

路徑:C:\Program Files\Photon Server\lib

Photon3DotNet.dll //普通的客戶端程序

Photon3Unity3D.dll //unity的客戶端程序

4.PhotonServerEngine下編寫具體的代碼

using UnityEngine;

using System.Collections;

using ExitGames.Client.Photon;

using System;

using System.Collections.Generic;

//讓當前類繼承IPhotonPeerListener,用於接收服務器的信息

public class PhotonServerEngine : MonoBehaviour, IPhotonPeerListener

{

private PhotonPeer peer;

private bool bConnet = false;

void Start()

{

//實例化一個PhotonPeer,

把當前類當成接收對象,使用TCP協議

peer = new PhotonPeer(this, ConnectionProtocol.Tcp);

//連接本地服務器 IP127.0.0.1 TCP端口號:4530

//通過PhotonServer.config文件,查找TCPListeners獲取TCP端口號

peer.Connect("127.0.0.1:4530", "ChatServer");

}

void Update()

{

//當每一幀時調用Service檢查消息隊列中的請求,並且發送請求

peer.Service();

}

void OnGUI()

{

if (bConnet)

{

if (GUILayout.Button("Send Operation"))

{

//與服務器端進行通信,發起請求

Dictionary<byte, object> dict = new Dictionary<byte, object>();

dict.Add(1, "UserName");

dict.Add(2, "UserPassWord");

peer.OpCustom(1, dict, true);

}

}

}

//當返回調試信息時被調用

public void DebugReturn(DebugLevel level, string message)

{

}

//當有新消息事件時被調用

public void OnEvent(EventData eventData)

{

}

  //當服務器端響應時被調用

  public void OnOperationResponse(OperationResponse operationResponse)

{

//接收服務器返回的數據

object ob_1 = null;

object ob_2 = null;

operationResponse.Parameters.TryGetValue(1, out ob_1);

operationResponse.Parameters.TryGetValue(2, out ob_2);

Debug.Log("UserName = " + ob_1.ToString() +"|" + "PassWord = " + ob_2.ToString());

}

//當狀態改變時調用

public void OnStatusChanged(StatusCode statusCode)

{

switch(statusCode)

{

case StatusCode.Connect:

bConnet = true;

Debug.Log("connect Succes");

break;

}

}

}

5.必須保證Server應用己啟動,未啟動的話先運行PhotonControl.exe,選擇default->start as appliaction, 如果正常顯示藍色圖標,出現異常顯示灰色圖標.

6.最後運行unity, start方法被調用連接本地服務器端的TCP端口,點擊GUI按鈕,發起請求.

搭建unity客戶端