打开Unity,创建一个新项目,新建文件夹Plugins,打开photon的lib文件夹,将Photon3Unity3D.dll拖入Plugins。 Plugins文件介绍: 如果做手机游戏开发一般 andoird 或者 ios 要接一些sdk 可以把sdk依赖的库文件 放在这里,比如 .so .jar .a 文件,这样打完包以后就会自动把这些文件打在你的包中。 新建C#脚本PhotonManger, 添加引用using ExitGames.Client.Photon; 添加接口IPhotonPeerListener,实现抽象类和构造函数。 PhotonManger.cs代码如下,我加的有注释:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ExitGames.Client.Photon;
using System;

public class PhotonManger : MonoBehaviour,IPhotonPeerListener
{
private PhotonPeer peer;
private ConnectionProtocol protocol = ConnectionProtocol.Udp; //udp传输协议 private string serverAddress = “127.0.0.1:5055”; //服务器目前的ip地址
private string applicationName = “ChatRoom”; //服务器程序名称

bool connected = false;

void Awake()
{
    peer = new PhotonPeer(this, protocol);
}

void Update ()
{
    if (!connected)
    {
        peer.Connect(serverAddress, applicationName);    //,如果服务器未连接,那么连接服务器
    }

    peer.Service();

    if(Input.GetKeyDown(KeyCode.Space))
    {
        var parameters = new Dictionary<byte,object>();    //字典
        parameters.Add(0, "武宝宝");
        peer.OpCustom(1, parameters, true);                //给服务器发请求
    }
}

/// <summary>
/// 服务器断开调用,避免Unity卡死,我一开始没写这个方法unity死了很多次
/// </summary>
void OnDestroy()
{
    peer.Disconnect();
}

/// <summary>
/// 返回时调用
/// </summary>
/// <param name="level"></param>
/// <param name="message"></param>
public void DebugReturn(DebugLevel level, string message)
{

}

public void OnEvent(EventData eventData)
{

}

/// <summary>
/// 服务器给客户端的响应
/// </summary>
/// <param name="operationResponse"></param>
public void OnOperationResponse(OperationResponse operationResponse)
{
    Debug.Log("服务器给客户端的响应");
}

/// <summary>
/// 连接状态改变
/// </summary>
/// <param name="statusCode"></param>
public void OnStatusChanged(StatusCode statusCode)
{
    Debug.Log(statusCode.ToString());
    switch(statusCode)
    {
        case StatusCode.Connect:
            connected = true;
            break;
        case StatusCode.Disconnect:
            connected = false;
            break;
    }
}

}

现在回到ChatRoom项目中, MyServer.cs代码如下:

using ExitGames.Logging;
using ExitGames.Logging.Log4Net;
using log4net;
using log4net.Config;
using Photon.SocketServer;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChatRoom
{
public class MyServer : ApplicationBase
{
private static readonly ILogger log = ExitGames.Logging.LogManager.GetCurrentClassLogger();

    /// <summary>
    /// 日志输出
    /// </summary>
    /// <param name="str"></param>
    public static void Log(string str)
    {
        log.Info(str.ToString());
    }

    /// <summary>
    /// 客户端连接
    /// </summary>
    /// <param name="initRequest"></param>
    /// <returns></returns>
    protected override PeerBase CreatePeer(InitRequest initRequest)
    {

        return new MyClient(initRequest);
    }

    /// <summary>
    /// 服务器启动时调用
    /// </summary>
    protected override void Setup()
    {
        InitLogging();
        Log("Setup OK");
    }

    /// <summary>
    /// 产生一个log文件,存放我们的log
    /// </summary>
    protected virtual void InitLogging()
    {
        ExitGames.Logging.LogManager.SetLoggerFactory(Log4NetLoggerFactory.Instance);
        GlobalContext.Properties\["Photon:ApplicationLogPath"\] = Path.Combine(this.ApplicationRootPath, "log");
        GlobalContext.Properties\["LogFileName"\] = "wjg" + this.ApplicationName;
        XmlConfigurator.ConfigureAndWatch(new FileInfo(Path.Combine(this.BinaryPath, "log4net.config")));
    }

    /// <summary>
    /// 服务器停止时调用的方法
    /// </summary>
    protected override void TearDown()
    {
        Log("TearDown OK");
    }
}

}

MyClient.cs代码如下:

using Photon.SocketServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using PhotonHostRuntimeInterfaces;

namespace ChatRoom
{
///


/// 客户端
///

class MyClient : ClientPeer
{
public MyClient(InitRequest initRequest) : base(initRequest)
{
MyServer.Log(“客户端上线”);
}

    /// <summary>
    /// 客户端断开连接
    /// </summary>
    /// <param name="reasonCode"></param>
    /// <param name="reasonDetail"></param>
    protected override void OnDisconnect(DisconnectReason reasonCode, string reasonDetail)
    {
        MyServer.Log("客户端下线");
    }

    /// <summary>
    /// 客户端发起请求
    /// </summary>
    /// <param name="operationRequest"></param>
    /// <param name="sendParameters"></param>
    protected override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters)
    {
        MyServer.Log("客户端发送请求");
        MyServer.Log(operationRequest.Parameters\[0\].ToString());

        //回调客户端,与PhotonManger中的OnOperationResponse相对应
        this.SendOperationResponse(new OperationResponse(), sendParameters);  
    }
}

}

把脚本PhotonManger.cs放到Main Camera身上,保存场景。 启动PhotonControl程序,启动ChatServer服务器。 打开日志,查看日志情况。[

](http://www.wjgbaby.com/wp-content/uploads/2017/08/17080435-300x38.png)](http://www.wjgbaby.com/wp-content/uploads/2017/08/17080435.png) [![](http://www.wjgbaby.com/wp-content/uploads/2017/08/17080434-300x55.png)](http://www.wjgbaby.com/wp-content/uploads/2017/08/17080434.png) 运行unity项目,Console输出出现Connect表示连接成功,Disconnected表示断开连接。 [![](http://www.wjgbaby.com/wp-content/uploads/2017/08/17080436-300x138.png)](http://www.wjgbaby.com/wp-content/uploads/2017/08/17080436.png)[![](http://www.wjgbaby.com/wp-content/uploads/2017/08/17080437-300x148.png)
在unity的scene场景按下空格键,Console出现“服务器给客户端的响应”,这表明我们PhotonManger里面的函数:peer.OpCustom和方法:OnOperationResponse()
方法调用成功。