Photon 서버 엔진 입문 강좌 2

7505 단어
이전 강의에서는 주로 서버의 간단한 지식, 서버와 클라이언트 연결을 설정했다.
둘째, 클라이언트 요청 서버, 서버 응답 조작을 소개합니다. 간단한 사용자 로그인을 바탕으로 소개하겠습니다.
1. 서버 측
이전 강좌에 따라 우리는 간단한 photon 서버를 설정했지만 서버 연결과 서버 끊기 작업에만 사용할 수 있습니다. 다른 것은 기본적으로 언급하지 않았습니다. 오늘은 이전 강좌를 바탕으로 내용을 추가하려고 합니다.
주로 마이피어에서.cs 클래스의 OnOperationRequest 메서드에서 구현되며 코드는 다음과 같습니다.
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
    }
}

2. 클라이언트
클라이언트 프로세스는 서버를 요청하고 서버의 응답 아래 위의 코드를 받아야 합니다.
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
}

프로젝트 원본 포인트 면제 다운로드: 서버 측과 클라이언트

좋은 웹페이지 즐겨찾기