Unity连Photon服务器入门详解

发表于2016-08-05
评论0 2k浏览
  Unity连Photon服务器入门详解

  Photon是目前比较好用的游戏服务器。目前网上对于Photon的服务器讲解比较少,最近也对Photon做了初步的了解,做一个极其详细的入门。
  首先就是得下载Photon咯
  http://www.photonengine.com/en/OnPremise/Download   这个是服务器下载。(上传图片的功能崩溃了。。。)
  http://www.photonengine.com/en/OnPremise/Dashboard (得注册账号哦。。。)
  这里有个比较好的教程http://download.csdn.net/download/a762923309/4936547  是免费的,下载就好(CSDN的)
  http:///www.cnblogs.com/liusuqi/category/447143.html   这个博客对Photon的讲解非常好如果你能看懂教程就可以右上角了。
  现在开始正题。在服务器的deploy中是配置所有服务器的,会看到有几个启动版本bin_Win32,bin_Win32_xp,根据自己的系统环境来选择。
  我系统是win10选的就是bin_Win64 里面有个PhotonControl.exe就是运行服务器。双击启动它。
  在你的系统右下角就会发现一个小圆圈,这个就是服务器啦!
  右键它你会发现有个Photon instance:下面有个Default就是我们要用的服务器啦,上面的教程中这里是不同的,不过没差多少。
  对了,下载下来的权限就放在这个bin文件夹,我的就是bin_Win64,弄完权限记得重启服务器啊。
  下面我们就来写一下服务器代码。一个简单的用户登录
  Photon用的C#我们就用VS写,我用的是VS2015
  首先我们新建一个C#类库我们叫MyServer,让我们引入3个dll,在Photon的lib中
  ExitGamesLibs.dll
  Photon.SocketServer.dll
  PhotonHostRuntimeInterfaces.dll
  新建一个C#类我们叫MyPeer,继承PeerBase,然后重写函数,别忘了using  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using Photon.SocketServer;
using PhotonHostRuntimeInterfaces;
 
namespace MyServer
{
    using Message;
    using System.Collections;
 
    public class MyPeer : PeerBase
    {
 
        Hashtable userTabel;
 
        public MyPeer(IRpcProtocol protocol,IPhotonPeer photonPeer) : base(protocol, photonPeer)
        {
            userTabel = new Hashtable();
            userTabel.Add("123", "1234");
        }
 
        protected override void OnDisconnect(DisconnectReason reasonCode, string reasonDetail)
        {
            //失去连线时候要处理的事项,例如释放资源
        }
 
        protected override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters)
        {
            //取得Client端传过来的要求加以处理
            switch (operationRequest.OperationCode)
            {
                case (byte)OpCodeEnum.Login:
                    string uname = (string)operationRequest.Parameters[(byte)OpKeyEnum.UserName];
                    string pwd = (string)operationRequest.Parameters[(byte)OpKeyEnum.PassWord];
                     
                    if (userTabel.ContainsKey(uname) && userTabel[uname].Equals(pwd))
                    {
                        SendOperationResponse(new OperationResponse((byte)OpCodeEnum.LoginSuccess, null), new SendParameters());
                    }
                    else
                    {
                        SendOperationResponse(new OperationResponse((byte)OpCodeEnum.LoginFailed, null), new SendParameters());
                    }
                    break;
            }
        }
    }
}
  然后我们再建一个C#类叫MyApplication,我们继承AppLicationBase,然后全部重写就好,每个函数的意思我都给出来了 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using Photon.SocketServer;
 
namespace MyServer
{
    public class MyApplication : ApplicationBase
    {
        protected override PeerBase CreatePeer(InitRequest initRequest)
        {
            //建立连线并回传给Photon Server
            return new MyPeer(initRequest.Protocol, initRequest.PhotonPeer);
        }
 
        protected override void Setup()
        {
            //初始化GameServer
        }
 
        protected override void TearDown()
        {
            //关闭GameServer并释放资源
        }
    }
}
  还有个Message是用来标识状态的,同样新建一个C#类叫Message  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
namespace MyServer.Message
{
    enum OpCodeEnum : byte
    {
        Login = 1,
        LoginSuccess = 2,
        LoginFailed = 3,
 
        Create = 250,
        Join = 255,
        Leave = 254,
        RaiseEvent = 253,
        SetProperties = 252,
        GetProperties = 251
    }
 
    enum OpKeyEnum : byte
    {
        RoomId = 251,
        UserName = 252,
        PassWord = 253
    }
}
  然后比较重要的一步,在VS中的解决方案中,我们右键我们的MyServer(C#类库名)打开属性,选择生成,把输出中的输出路径改为bin
  因为Photon就读取bin目录中的dll。
  然后我们就生成服务器就好啦~~~
  然后把我们的服务器MyServer中除了bin文件夹其他都可以删除,然后放到Photon中的deploy文件夹中,然后我们来配置一下Photon
  打开deploy目录中的bin目录,我就打开bin_Win64中的PhotonServer.config,用VS打开即可
  建议阅读PhotonServer.config文件中的注释,不会英语的可以用有道。很有帮助
  我们用的是Udp的传输方式,Photon只有一个接听端口就是5055,所以防火墙不要封这个端口还有843,是Unity和Flash的一个接通端口所以也不要封,防火墙不会开固定端口的见
  然后我们要加一段代码在下面 
1
2
3
      "MyServer" basedirectory="MyServer" assembly="MyServer" type="MyServer.MyApplication" forceautorestart="true" watchfiles="dll;config" excludefiles="log4net.config">
      
  然后保存即可。
  这样我们服务器端就配置完成了,现在让我们打开Default中的Start as application,然后打开Open Logs 见到Server is running。。。表面服务器建立成功了。
  然后就是Unity端了
  我们新建一个工程,然后引入一个dll直接拖到Unity中就行Photon3Unity3D.dll 同样也在lib中。
  让我们建一个C# Script 叫hotonSocket,同样在引用中导入Photon3Unity3D.dll  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using UnityEngine;
using ExitGames.Client.Photon;
using System.Collections.Generic;
 
public class PhotonSocket : MonoBehaviour,IPhotonPeerListener {
 
    #region 单例
 
    private static PhotonSocket _Instance;
 
    public static PhotonSocket Instance
    {
        get { return _Instance; }
    }
 
    #endregion
 
    private string address; //最好在Awake或Start中赋值,Unity 小问题,容易造成值不更改,还有最好写成私有
    private string Server; //同上
    private PhotonPeer peer;
 
    public ClientState state;
 
    void Awake ()
    {
        _Instance = this;
        address = "localhost:5055";
        Server = "MyServer";
        state = ClientState.DisConnect;
        peer = new PhotonPeer(this, ConnectionProtocol.Udp);
        peer.Connect(address, Server);
    }
 
    public void SendMessage(byte Code,Dictionary<byte,object> param)
    {
        peer.OpCustom(Code, param,true);
    }
 
    void Update ()
    {
        peer.Service();
    }
 
    public void DebugReturn(DebugLevel level, string message)
    {
    }
 
    public void OnEvent(EventData eventData)
    {
    }
 
    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;
                break;
        }
    }
 
    public void OnStatusChanged(StatusCode statusCode)
    {
        switch(statusCode)
        {
            case StatusCode.Connect:
                Debug.Log("Connect");
                break;
            case StatusCode.Disconnect:
                Debug.Log("DisConnect");
                break;
        }
    }
 
    public enum ClientState : byte
    {
        DisConnect,
        Connect,
        LoginSuccess,
        LoginFailed
    }
 
    enum OpCodeEnum : byte
    {
        //Login
        Login = 1,
        LoginSuccess = 2,
        LoginFailed = 3,
    }
}byte,object>
  这样Unity的部分也完事了,就可以来测试啦,出现Connect的Debug就表面链接服务器成功,出现LoginSuccess就OK了。
  以上的都是我们在教程中都能找到的部分,然后我们来说说教程中没有的Unity部分的address。
  如果想局域网联机的就要找到你的本机内网IP,然后让address = 本机IP:5055 这样就OK了,
  如果要想要外网链接呢有两种情况,一种你是用路由器的,也有两种方式,一种开DMZ主机,一种开虚拟服务器。
  第一种DMZ主机,不建议用这种方式,他会把你的IP完全暴露在外网,不安全, address = 外网IP:5055
  第二种虚拟服务器,这种方式就是开放部分端口,比较高端的路由器可以设置端口对端口,不高端的路由器只能指定端口,address = WAN口IP:5055
  没有服务器的呢,下一个花生壳软件,他会给你一个免费的域名,然后挂在你的外网IP上然后 address = 花生壳域名:5055

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引