unity基础开发----Photon服务器引擎 入门教程二

上一讲中主要介绍了服务器的简单知识,配置服务器和客户端连接.

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

一、服务器端

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

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

  1. using System;
  2. using System.Collections.Generic;
  3. using Photon.SocketServer;
  4. using PhotonHostRuntimeInterfaces;
  5. namespace MyServer
  6. {
  7. using Message;
  8. using System.Collections;
  9. public class MyPeer : PeerBase
  10. {
  11. Hashtable userTable;
  12. public MyPeer(IRpcProtocol protocol,IPhotonPeer photonPeer)
  13. : base(protocol, photonPeer)
  14. {
  15. userTable = new Hashtable();
  16. userTable.Add("user1","pwd1");
  17. userTable.Add("user2", "pwd2");
  18. userTable.Add("user3","pwd3");
  19. userTable.Add("user4", "pwd4");
  20. userTable.Add("user5","pwd5");
  21. }
  22. protected overridevoid OnDisconnect(PhotonHostRuntimeInterfaces.DisconnectReason reasonCode,string reasonDetail)
  23. {
  24. }
  25. protected override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters)
  26. {
  27. switch (operationRequest.OperationCode) {
  28. case (byte)OpCodeEnum.Login:
  29. string uname = (string)operationRequest.Parameters[(byte)OpKeyEnum.UserName];
  30. string pwd = (string)operationRequest.Parameters[(byte)OpKeyEnum.PassWord];
  31. if (userTable.ContainsKey(uname) && userTable[uname].Equals(pwd))//login success
  32. {
  33. SendOperationResponse(new OperationResponse((byte)OpCodeEnum.LoginSuccess,null),new SendParameters());
  34. }
  35. else
  36. { //login fauled
  37. SendOperationResponse(new OperationResponse((byte)OpCodeEnum.LoginFailed,null), new SendParameters());
  38. }
  39. break;
  40. }
  41. }
  42. }
  43. }
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方法中验证用户名和密码,然后发送响应给客户端.需要用到的枚举一个类如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace MyServer.Message
  6. {
  7. enum OpCodeEnum : byte
  8. {
  9. //login
  10. Login = 249,
  11. LoginSuccess = 248,
  12. LoginFailed = 247,
  13. //room
  14. Create = 250,
  15. Join = 255,
  16. Leave = 254,
  17. RaiseEvent = 253,
  18. SetProperties = 252,
  19. GetProperties = 251
  20. }
  21. enum OpKeyEnum : byte
  22. {
  23. RoomId = 251,
  24. UserName = 252,
  25. PassWord = 253
  26. }
  27. }
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  
    }  
} 

二、客户端

客户端过程需要请求服务器并接收服务器的响应下面上代码,就一个类搞定:

  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using ExitGames.Client.Photon;
  5. public class TestConnection : MonoBehaviour,IPhotonPeerListener {
  6. public string address;
  7. PhotonPeer peer;
  8. ClientState state = ClientState.DisConnect;
  9. string username ="";
  10. string password = "";
  11. // Use this for initialization
  12. void Start () {
  13. peer = new PhotonPeer(this,ConnectionProtocol.Udp);
  14. }
  15. // Update is called once per frame
  16. void Update () {
  17. peer.Service();
  18. }
  19. public GUISkin skin;
  20. void OnGUI(){
  21. GUI.skin = skin;
  22. switch(state){
  23. case ClientState.DisConnect:
  24. GUI.Label(new Rect(Screen.width/2,Screen.height/2-30,300,40),"click the button to connect.");
  25. if(GUI.Button(new Rect(Screen.width/2,Screen.height/2,100,30),"Connect")){
  26. peer.Connect(address,"MyServer");
  27. state = ClientState.Connecting;
  28. }
  29. break;
  30. case ClientState.Connecting:
  31. GUI.Label(new Rect(Screen.width/2,Screen.height/2-30,300,40),"Connecting to Server...");
  32. break;
  33. case ClientState.Connected:
  34. GUILayout.BeginArea(new Rect((Screen.width-500)/2,(Screen.height-400)/2,500,400));
  35. //
  36. GUILayout.BeginVertical();
  37. GUILayout.Label("Connect Success! Please Login.");
  38. //draw username
  39. GUILayout.BeginHorizontal();
  40. GUILayout.Label("UserName:");
  41. username = GUILayout.TextField(username);
  42. GUILayout.EndVertical();
  43. //draw password
  44. GUILayout.BeginHorizontal();
  45. GUILayout.Label("Password:");
  46. password = GUILayout.TextField(password);
  47. GUILayout.EndVertical();
  48. //draw buttons
  49. GUILayout.BeginHorizontal();
  50. if(GUILayout.Button("login")){
  51. userLogin(username,password);
  52. }
  53. if(GUILayout.Button("canel")){
  54. state = ClientState.DisConnect;
  55. }
  56. GUILayout.EndVertical();
  57. GUILayout.EndVertical();
  58. GUILayout.EndArea();
  59. break;
  60. case ClientState.ConnectFailed:
  61. GUI.Label(new Rect(Screen.width/2,Screen.height/2-30,300,40),"Connect Failed.");
  62. break;
  63. case ClientState.LoginSuccess:
  64. GUILayout.BeginArea(new Rect((Screen.width-500)/2,(Screen.height-400)/2,500,400));
  65. GUILayout.Label("Login Success!");
  66. GUILayout.EndArea();
  67. break;
  68. case ClientState.LoginFailed:
  69. GUILayout.BeginArea(new Rect((Screen.width-500)/2,(Screen.height-400)/2,500,400));
  70. GUILayout.Label("Login Failed!");
  71. GUILayout.EndArea();
  72. break;
  73. }
  74. }
  75. #region My Method
  76. IEnumerator connectFailedHandle(){
  77. yield return new WaitForSeconds(1);
  78. state = ClientState.DisConnect;
  79. }
  80. void userLogin(string uname,string pwd){
  81. Debug.Log("userLogin");
  82. Dictionary<byte,object> param =new Dictionary<byte,object>();
  83. param.Add((byte)OpKeyEnum.UserName,uname);
  84. param.Add((byte)OpKeyEnum.PassWord,pwd);
  85. peer.OpCustom((byte)OpCodeEnum.Login,param,true);
  86. }
  87. IEnumerator loginFailedHandle(){
  88. yield return new WaitForSeconds(1);
  89. Debug.Log("loginFailedHandle");
  90. state = ClientState.Connected;
  91. }
  92. #endregion
  93. #region IPhotonPeerListener implementation
  94. public void DebugReturn (DebugLevel level,string message)
  95. {
  96. }
  97. public void OnOperationResponse (OperationResponse operationResponse)
  98. {
  99. switch(operationResponse.OperationCode)
  100. {
  101. case (byte)OpCodeEnum.LoginSuccess:
  102. Debug.Log("login success!");
  103. state = ClientState.LoginSuccess;
  104. break;
  105. case (byte)OpCodeEnum.LoginFailed:
  106. Debug.Log("login Failed!");
  107. state = ClientState.LoginFailed;
  108. StartCoroutine(loginFailedHandle());
  109. break;
  110. }
  111. }
  112. public void OnStatusChanged (StatusCode statusCode)
  113. {
  114. switch(statusCode){
  115. case StatusCode.Connect:
  116. Debug.Log("Connect Success! Time:"+Time.time);
  117. state = ClientState.Connected;
  118. break;
  119. case StatusCode.Disconnect:
  120. state = ClientState.ConnectFailed;
  121. StartCoroutine(connectFailedHandle());
  122. Debug.Log("Disconnect! Time:"+Time.time);
  123. break;
  124. }
  125. }
  126. public void OnEvent (EventData eventData)
  127. {
  128. }
  129. #endregion
  130. }
  131. public enum ClientState :byte{
  132. DisConnect,
  133. Connecting,
  134. Connected,
  135. ConnectFailed,
  136. LoginSuccess,
  137. LoginFailed
  138. }
  139. public enum OpCodeEnum :byte
  140. {
  141. //login
  142. Login = 249,
  143. LoginSuccess = 248,
  144. LoginFailed = 247,
  145. //room
  146. Create = 250,
  147. Join = 255,
  148. Leave = 254,
  149. RaiseEvent = 253,
  150. SetProperties = 252,
  151. GetProperties = 251
  152. }
  153. public enum OpKeyEnum :byte
  154. {
  155. RoomId = 251,
  156. UserName = 252,
  157. PassWord = 253
  158. }
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  
}  

转载地址:http://blog.csdn.net/asd237241291/article/details/8820166


推荐博客:http://www.cnblogs.com/liusuqi/category/447143.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值