您的位置:首页 > 移动开发 > Unity3D

基于Unity创建PhotonServer服务器一:

2018-02-02 17:22 239 查看
1:新建一个Unity项目并且在项目中新建一个文件夹Plugins将Photon3Unity3D.dll放进这个文件夹

2:在主相机上添加一个名为PhotonServerEngine的脚本

3:打开脚本在Start方法里面new一个PhotonServer并且添加引用并且实现一下IPhotonPeerListener的接口:

public class PhotonServerEngine : MonoBehaviour,IPhotonPeerListener

{

    private PhotonPeer peer;

    private bool isConnected = false;//查看是否连接成功(监听器)

 

    void Start ()

    {

         peer = new PhotonPeer(this, ConnectionProtocol.Tcp);//this 表示用当前类充当Listener

        peer.Connect("127.0.0.1:4530","ChatServer");

    }

void Update ()

    {

        peer.Service();//每一帧都向服务器发送请求确认一下

}

    void OnGUI()

    {

        if (isConnected)//如果连接成功默认为true

        {

            if (GUILayout.Button("Send a operation."))//这里创建了一个button   每点击一次执行下面的方法

            {

                Dictionary<byte, object> dict = new Dictionary<byte, object>()

                {

                    {1,"username" },

                    {2,"password"}

                };

                peer.OpCustom(1,dict,true);

注释:peer.OpCustom(第一个参数是操作码,用来区分我们这个请求是用来干嘛的,第二个字典是用来存储我们的一些参数, 第三个参数表示发送的信息是否可靠,如果设置为true会确保发送到服务器端);

            }

        }

    }

    public void DebugReturn(DebugLevel level, string message)

    {

        Debug.Log(level + ":" + message);

    }

    public void OnEvent(EventData eventData)

   
9a25
{

        throw new System.NotImplementedException();

    }

    public void OnOperationResponse(OperationResponse operationResponse)

    {

        Dictionary<byte, object> dict = operationResponse.Parameters;

        object v = null;

        dict.TryGetValue(1,out v);

        Debug.Log("Get value from server."+v.ToString());

    }

    //客户端和服务器端连接发生变化时调用

    public void OnStatusChanged(StatusCode statusCode)

    {

        switch (statusCode)

        {

            case StatusCode.Connect:

                isConnected = true;

                Debug.Log("Connected success.");

                break; 

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PhotonServer之Unity