unity连接Photon

一、文件的操作

将dll文件复制到Unity文件夹下

DLL文件必须放在Plugins文件夹里,并且这个文件夹名字不能错,Unity会事先加载预编译

二、代码

服务端

using ExitGames.Logging;
using ExitGames.Logging.Log4Net;
using log4net.Config;
using Photon.SocketServer;
using System.IO;

namespace CJHGameServer
{
    //所有的server,都要继承 Photon 里的 ApplicationBase,然后实现ApplicationBase的三个方法,
    class MyGameServer : ApplicationBase
    {
        public static readonly ILogger log = LogManager.GetCurrentClassLogger();//获取当前LOG类
        //当有一个客户端连接上以后,就会执行这个方法
        protected override PeerBase CreatePeer(InitRequest initRequest)
        {
            log.Info("一个客户端连接");
            return new ClientPeer(initRequest);//创建客户端
        }
        //服务器初始化函数
        protected override void Setup()
        {
            //拼路径
            log4net.GlobalContext.Properties["Photon:ApplicationLogPath"] = Path.Combine(
                Path.Combine(this.ApplicationRootPath,"bin_Win64"),"log");//生成log文件
            FileInfo configFileInfo = new FileInfo(Path.Combine(this.BinaryPath,"log4net.config"));//设置配置的路径
            if (configFileInfo.Exists)//判断文件是否存在
            {
                LogManager.SetLoggerFactory(Log4NetLoggerFactory.Instance);//让photon知道日志输出
                XmlConfigurator.ConfigureAndWatch(configFileInfo);//读取配置
            }
            log.Info("服务器启动啦");
        }
        //服务器关闭函数
        protected override void TearDown()
        {
            log.Info("服务器关闭啦");
        }
    }
}
using System.Collections.Generic;
using Photon.SocketServer;
using PhotonHostRuntimeInterfaces;

namespace CJHGameServer
{
    //客户端连接
    class ClientPeer : Photon.SocketServer.ClientPeer
    {
        public ClientPeer(InitRequest initRequest) : base(initRequest)
        {
        }

        //当每个客户端断开时
        protected override void OnDisconnect(DisconnectReason reasonCode, string reasonDetail)
        {

        }
        //客户端发起请求的时候
        protected override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters)
        {
            switch (operationRequest.OperationCode)
            {
                case 1:
                    //------解析客户端发送过来的数据-------------
                    var data = operationRequest.Parameters;
                    object intValue;
                    data.TryGetValue(1, out intValue);//这种写法避免了字典里没有这个KEY
                    object StringValue;
                    data.TryGetValue(2, out StringValue);
                    MyGameServer.log.Info("收到客户端的请求,OpCode:1 " + intValue.ToString() + ":" + StringValue.ToString());

                    //-----------向客户端发送消息---------------
                    //返回响应  //创建消息,参数:消息号
                    OperationResponse opResponse = new OperationResponse(operationRequest.OperationCode);
                    //构造参数
                    var data2 = new Dictionary<byte, object>();
                    data2.Add(1, 100);
                    data2.Add(2, "这个是参数,服务器发来的");
                    opResponse.SetParameters(data2);

                    //返回code,为发送过来的code,返回的参数,为发送过来的参数
                    SendOperationResponse(opResponse, sendParameters);//向客户端发送消息

                    //推送一个Event
                    EventData ed = new EventData(1);
                    var data3 = new Dictionary<byte, object>();
                    data3.Add(1, 100);
                    data3.Add(2, "这个是参数,服务器推送的");
                    ed.Parameters = data3;
                    SendEvent(ed, new SendParameters());
                    break;
            }            
        }
    }
}

客户端

public class test : MonoBehaviour {

	void Start () {
		
	}
	
	void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            SendRequest();
        }
	}

    private void SendRequest()
    {
        //构造参数
        var data = new Dictionary<byte, object>();
        data.Add(1, 100);
        data.Add(2, "这个是参数");
        //发送   参数1:操作码,服务端返回时用
        PhotonEngine.peer.OpCustom(1,data,true);
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ExitGames.Client.Photon;

public class PhotonEngine : MonoBehaviour,IPhotonPeerListener {
    private static PhotonEngine Instance;
    public static PhotonPeer peer;//连接

    private void Awake()
    {
        if(Instance == null)
        {
            Instance = this; //当脚本直接绑定到组件上时,不用new直接用this
            //当前GameObject不会随场景的销毁而销毁
            DontDestroyOnLoad(this.gameObject);
        }
    }


    // Use this for initialization
    void Start () {
        //建立连接 参数:1、自己,2、连接方式
        peer = new PhotonPeer(this,ConnectionProtocol.Udp);
        //连接 参数:1、IP地址+端口号
        peer.Connect("127.0.0.1:5055", "MyGame6");
	}
	
	// Update is called once per frame
	void Update () {
        peer.Service();//打开服务
	}

    private void OnDestroy()
    {
        //关闭连接
        if (peer != null && peer.PeerState == PeerStateValue.Connected)
        {
            //如果是连接状态
            peer.Disconnect();
        }
    }

    public void DebugReturn(DebugLevel level, string message)
    {
        
    }
    //服务器主动发送事件时调用
    public void OnEvent(EventData eventData)
    {
        switch (eventData.Code)
        {
            case 1:
                Debug.Log("收到服务器的Event推送,OpCode:1");
                //----解析服务端推送的数据---
                var data = eventData.Parameters;
                object intValue, StringValue;
                data.TryGetValue(1, out intValue);//这种写法避免了字典里没有这个KEY                
                data.TryGetValue(2, out StringValue);
                Debug.Log("收到服务端的推送,OpCode:1 " + intValue.ToString() + ":" + StringValue.ToString());
                break;
            default:
                break;
        }
    }
    //客户端发送消息给服务端,服务端返回消息时调用
    public void OnOperationResponse(OperationResponse operationResponse)
    {
        switch (operationResponse.OperationCode)
        {
            case 1:
                Debug.Log("收到服务器的响应,OpCode:1");

                //----解析服务端发送的数据---
                var data = operationResponse.Parameters;
                object intValue;
                data.TryGetValue(1, out intValue);//这种写法避免了字典里没有这个KEY
                object StringValue;
                data.TryGetValue(2, out StringValue);
                Debug.Log("收到服务端的请求,OpCode:1 " + intValue.ToString() + ":" + StringValue.ToString());
                break;
            default:
                break;
        }
    }

    public void OnStatusChanged(StatusCode statusCode)
    {
        Debug.LogError(statusCode);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值