Photon学习笔记(一)

公司需求要了解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
}



 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值