【3D技术宅公社】XR数字艺术论坛  XR技术讨论 XR互动电影 定格动画

 找回密码
 立即注册

QQ登录

只需一步,快速开始

调查问卷
论坛即将给大家带来全新的技术服务,面向三围图形学、游戏、动画的全新服务论坛升级为UTF8版本后,中文用户名和用户密码中有中文的都无法登陆,请发邮件到324007255(at)QQ.com联系手动修改密码

3D技术论坛将以计算机图形学为核心,面向教育 推出国内的三维教育引擎该项目在持续研发当中,感谢大家的关注。

查看: 5737|回复: 5

[多人在线技术] Unity 服务器 Photon中文入门

[复制链接]
发表于 2014-2-12 10:55:35 | 显示全部楼层 |阅读模式
金山快盘附件Photon中文版介绍文档.pdf(1.22MB)


服务器 Photon  100人无时间限制版
游客,如果您要查看本帖隐藏内容请回复



以下转自网络
Photon服务器引擎 入门教程一

Photon是个好东西,但是网上的入门教程太少了,特别是中文版的。小弟就自己琢磨吧,下面一系列是对Photon的研究过程,如有哪个地方写的有误,望请前辈指教。

首先去PhotonServer SDK下载服务器端SDK,需要登录的,就先注册一个账号吧.

解压出来是四个文件

deploy:主要存放photon的服务器控制程序和服务端Demo

doc:顾名思义,文档

lib:Photon类库,开发服务端需要引用的

src-server:服务端Demo源代码


今天搞一个客户端连接服务器最简单的程序,也算是hello world吧

客户端以Unity3d 为基础,hello world包括配置服务器,客户端,客户端连接服务器,客户端状态改变。

第一步:配置服务器端

打开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,写法如下:

[mw_shl_code=csharp,true]using System;
using System.Collections.Generic;  
using Photon.SocketServer;  
using PhotonHostRuntimeInterfaces;  
  
namespace MyServer  
{  
    public class MyPeer : PeerBase  
    {  
  
        public  MyPeer(IRpcProtocol protocol,IPhotonPeer photonPeer)  
            : base(protocol, photonPeer)  
        {   
              
        }  
  
        protected override void OnDisconnect(PhotonHostRuntimeInterfaces.DisconnectReason reasonCode, string reasonDetail)  
        {  
              
        }  
  
        protected override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters)  
        {  
              
        }  
    }  
}  [/mw_shl_code]

接上,MyApplication.cs类这样写:[mw_shl_code=csharp,true]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()  
        {  
              
        }  
    }  
}  [/mw_shl_code]完成后,在解决方案资源管理器中选中当前项目,打开属性,选择生成选项卡,把输出路径改成bin\,然后就生成类库吧

复制当前项目下MyServer文件夹到deploy文件夹下,删除除了bin文件夹以外其他所有文件和文件夹,然后文本编辑器打开deploy\bin_Win64\PhotonServer.config配置文件(我的是win7 64位机器,就选择这个),添加以下配置:

[mw_shl_code=html,true]<Application
                Name="MyServer"  
                BaseDirectory="MyServer"  
                Assembly="MyServer"  
                Type="MyServer.MyApplication"  
                EnableAutoRestart="true"  
                WatchFiles="dll;config"  
                ExcludeFiles="log4net.config">[/mw_shl_code]

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中,新建脚本TestConnection.cs,脚本代码如下:

[mw_shl_code=csharp,true]using UnityEngine;
using System.Collections;  
  
using ExitGames.Client.Photon;  
  
public class TestConnection : MonoBehaviour,IPhotonPeerListener {  
    public PhotonPeer peer;  
    // Use this for initialization  
    void Start () {  
        peer = new PhotonPeer(this,ConnectionProtocol.Udp);  
    }  
      
    // Update is called once per frame  
    void Update () {  
        peer.Service();  
    }  
      
    void OnGUI(){  
        if(GUI.Button(new Rect(Screen.width/2,Screen.height/2,200,100),"Connect")){  
            peer.Connect("localhost:5055","MyServer");  
        }  
    }  

    #region IPhotonPeerListener implementation  
    public void DebugReturn (DebugLevel level, string message)  
    {  
         
    }  
  
    public void OnOperationResponse (OperationResponse operationResponse)  
    {  
         
    }  
  
    public void OnStatusChanged (StatusCode statusCode)  
    {  
        switch(statusCode){  
        case StatusCode.Connect:  
            Debug.Log("Connect Success!");  
            break;  
        case StatusCode.Disconnect:  
            Debug.Log("Disconnect!");  
            break;  
        }  
    }  
  
    public void OnEvent (EventData eventData)  
    {  
         
    }  
    #endregion  
}  [/mw_shl_code]

把脚本绑定到场景中物体上,运行后可以看到一个按钮,点击连接,如果连接成功会打印"Connect Success!".

Unity客户端例子到这里下载


 楼主| 发表于 2014-2-12 11:00:37 | 显示全部楼层
Photon服务器引擎 入门教程二

第二讲介绍客户端请求服务器,服务器响应操作,我们就以一个简单的用户登录为基础介绍吧


一、服务器端

按照上一篇教程我们配置好简单的photon服务器,但是只能用于连接服务器和断开服务器操作,其他的基本没有提到,今天是要在上一讲基础上添加内容.

主要是在MyPeer.cs类的OnOperationRequest方法中实现,代码如下:

[mw_shl_code=csharp,true]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;  
            }  
        }  
    }  
} [/mw_shl_code]

OnOperationRequest方法中验证用户名和密码,然后发送响应给客户端.需要用到的枚举一个类如下:[mw_shl_code=csharp,true]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  
    }  
}  [/mw_shl_code]二、客户端客户端过程需要请求服务器并接收服务器的响应下面上代码,就一个类搞定:[mw_shl_code=csharp,true]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  
}  [/mw_shl_code]项目源码免积分下载:服务器端客户端
 楼主| 发表于 2014-2-12 11:13:36 | 显示全部楼层
运行PhotonControl 会出现几秒钟后自动停止
刚开始用的时候出现这种问题,感觉很困扰,后来总结一下可能原因有以下几种:
1、证书校验没有通过:证书过期或者没有连上浮动证书服务器
2、端口被占用:如酷狗占了848端口或者9090端口被占用;
3、某个应用的程序有问题,也会导致Photon引擎启动不了,一般需要检查应用入口类的构造方法以及setup等方法。
发表于 2014-2-16 13:49:44 | 显示全部楼层
好东西!支持!
发表于 2014-2-18 09:58:23 | 显示全部楼层
好东西!支持!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|3D数字艺术论坛 ( 沪ICP备14023054号 )

GMT+8, 2024-4-20 11:10

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表