文章目录
- Unity进阶--使用PhotonServer实现服务端和客户端通信
- 服务器的安装和配置
- 添加日志
- 客户端的配置
- 客户端和服务器的通信
- Dlc 出现vscode引用不好使的时候
 
Unity进阶–使用PhotonServer实现服务端和客户端通信
服务器的安装和配置
Photon的地址:https://www.photonengine.com/zh-cn/sdks
- 下载对应的sdk:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nqhFg3FR-1691110946416)(../AppData/Roaming/Typora/typora-user-images/image-20230802150527693.png)]](https://img-blog.csdnimg.cn/ec9d3b7517354d218cb2a8dffe117f51.png)
- 在Visual studio 里创建新的类库:
![**[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YNC7wHVC-1691110946416)(../AppData/Roaming/Typora/typora-user-images/image-20230802151715763.png)]**](https://img-blog.csdnimg.cn/170fd0808ba44086b8b651a343cd9f79.png)
在项目里添加对应的dll文件引用:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SfcLhTkB-1691110946417)(../AppData/Roaming/Typora/typora-user-images/image-20230802160144216.png)]](https://img-blog.csdnimg.cn/71c5a553bf8e47b8b4b5b66e52e823b7.png)
在这个文件夹里找:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-v58YvXYT-1691110946417)(../AppData/Roaming/Typora/typora-user-images/image-20230802175928178.png)]](https://img-blog.csdnimg.cn/07b51b15a9b84527aac3c4b7ee20f6a0.png)
这五个插件:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XdLbRv77-1691110946417)(../AppData/Roaming/Typora/typora-user-images/image-20230802160856827.png)]](https://img-blog.csdnimg.cn/204421bd0a44486ea14c627260525fba.png)
编写服务器端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Photon.SocketServer;namespace PhotonServerFirst
{public class PSTest : ApplicationBase{protected override PeerBase CreatePeer(InitRequest initRequest){ return new PSpeer(initRequest);}protected override void Setup(){}protected override void TearDown(){}}
}编写客户端模板
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Photon.SocketServer;
using PhotonHostRuntimeInterfaces;namespace PhotonServerFirst
{public class PSpeer : ClientPeer{public PSpeer(InitRequest initRequest) : base(initRequest){}protected override void OnDisconnect(DisconnectReason reasonCode, string reasonDetail){throw new NotImplementedException();}protected override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters){throw new NotImplementedException();}}
}创建服务器文件
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9g2BXhfS-1691110946417)(../AppData/Roaming/Typora/typora-user-images/image-20230802152237347.png)]](https://img-blog.csdnimg.cn/c20fe0772efb4b2598dea357be861673.png)
- 修改生成目录:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OZs48M4L-1691110946418)(../AppData/Roaming/Typora/typora-user-images/image-20230802182536425.png)]](https://img-blog.csdnimg.cn/4e64ee844dbc4aea8e0efed0e79ca34c.png)
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Dvn72gRd-1691110946418)(../AppData/Roaming/Typora/typora-user-images/image-20230802182941475.png)]](https://img-blog.csdnimg.cn/b777b7dc1b7b4d87ad2e413bf51e8115.png)
放到之前创建的bin里。
然后生成。
- 修改PhotonServer配置文件
在![在[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-H5BLT0QY-1691110946420)(../AppData/Roaming/Typora/typora-user-images/image-20230803090947410.png)]](https://img-blog.csdnimg.cn/690dfc2ddd954db0893e079fc8085055.png)
 寻找
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PpBI5krl-1691110946424)(../AppData/Roaming/Typora/typora-user-images/image-20230803091005322.png)]](https://img-blog.csdnimg.cn/0f018242073743d0a0fe051e633ba440.png)
-  配置文件: <!-- DisplayName:显示名称 --><PhotonServerFirstMaxMessageSize="512000"MaxQueuedDataPerPeer="512000"PerPeerMaxReliableDataInTransit="51200"PerPeerTransmitRateLimitKBSec="256"PerPeerTransmitRatePeriodMilliseconds="200"MinimumTimeout="5000"MaximumTimeout="30000"DisplayName="PhotonServerFirst"><!-- 0.0.0.0 opens listeners on all available IPs. Machines with multiple IPs should define the correct one here. --><!-- Port 5055 is Photon's default for UDP connections. --><UDPListeners><UDPListenerIPAddress="0.0.0.0"Port="5055"OverrideApplication="PhotonServerFirst"></UDPListener></UDPListeners><!-- 0.0.0.0 opens listeners on all available IPs. Machines with multiple IPs should define the correct one here. --><!-- Port 4530 is Photon's default for TCP connecttions. --><!-- A Policy application is defined in case that policy requests are sent to this listener (known bug of some some flash clients) --> <TCPListeners><TCPListenerIPAddress="0.0.0.0"Port="4530"PolicyFile="Policy\assets\socket-policy.xml"InactivityTimeout="10000"OverrideApplication="PhotonServerFirst" ></TCPListener></TCPListeners><!-- Defines the Photon Runtime Assembly to use. --><RuntimeAssembly="PhotonHostRuntime, Culture=neutral"Type="PhotonHostRuntime.PhotonDomainManager"UnhandledExceptionPolicy="Ignore"></Runtime><Applications Default="PhotonServerFirst"><!-- Name:要注意和上面填写的应用名字相同 --><!--BaseDirectory:编译好的dll所在文件夹名--><!--Assembly:dll名--><!--Type:命名空间.类名--><ApplicationName="PhotonServerFirst"BaseDirectory="PhotonServerFirst"Assembly="PhotonServerFirst"Type="PhotonServerFirst.PSTest"ForceAutoRestart="true"WatchFiles="dll;config"ExcludeFiles="log4net.config"></Application></Applications></PhotonServerFirst>这样photonServer下就有我们创建的服务器了。 
添加日志
-  在 ![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ocfdDxLc-1691110946425)(../AppData/Roaming/Typora/typora-user-images/image-20230803092647288.png)]](https://img-blog.csdnimg.cn/57105f5956fd42a2bdba490e10965d1e.png) 
 下寻找log4net.config把它复制到工程里面。
-  然后把属性改为始终复制 ![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wJQkJxCi-1691110946427)(../AppData/Roaming/Typora/typora-user-images/image-20230803092916486.png)]](https://img-blog.csdnimg.cn/3b7e8980ac1b454abdc88ba92e72dd1d.png) 
-  改一下输出的日志名字 <file type="log4net.Util.PatternString" value="%property{Photon:ApplicationLogPath}\\PhotonServerFirst.Server.log" />
-  配置服务器程序 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Photon.SocketServer; using ExitGames.Logging; using ExitGames.Logging.Log4Net; using log4net.Config; using System.IO;namespace PhotonServerFirst {public class PSTest : ApplicationBase{//日志需要的private static readonly ILogger log = LogManager.GetCurrentClassLogger();protected override PeerBase CreatePeer(InitRequest initRequest){ return new PSpeer(initRequest);}//初始化protected override void Setup(){InitLog();}//server端关闭的时候protected override void TearDown(){}#region 日志/// <summary>/// 初始化日志以及配置/// </summary>private void InitLog(){//日志的初始化log4net.GlobalContext.Properties["Photon:ApplicationLogPath"] = this.ApplicationRootPath + @"\bin_Win64\log";//设置日志的路径FileInfo configFileInfo = new FileInfo(this.BinaryPath + @"\log4net.config");//获取配置文件if (configFileInfo.Exists){//对photonserver设置日志为log4netLogManager.SetLoggerFactory(Log4NetLoggerFactory.Instance);XmlConfigurator.ConfigureAndWatch(configFileInfo);log.Info("初始化成功");}}#endregion } }
-  打开photonserver运行应用,日志输出则配置成功。 
客户端的配置
- 在Photon-OnPremise-Server-SDK_v4-0-29-11263 > lib >下寻找Photon3Unity3D.dll放到unity3d的插件文件夹(Pluigins)里。
- 编写客户端脚本绑定到一个单例不会被销毁的组件里。(代码如下)
客户端和服务器的通信
-  客户端 using System.Collections; using System.Collections.Generic; using UnityEngine; using ExitGames.Client.Photon;public class PhotonManager : MyrSingletonBase<PhotonManager>, IPhotonPeerListener {private PhotonPeer peer;void Awake() {DontDestroyOnLoad(this);}// Start is called before the first frame updatevoid Start(){peer = new PhotonPeer(this, ConnectionProtocol.Tcp);peer.Connect("127.0.0.1:4530", "PhotonServerFirst");}void Update(){peer.Service();if (Input.GetKeyDown(KeyCode.Space)){Dictionary<byte, object> dic = new Dictionary<byte, object>();dic.Add(1,"你好,我是王小虎");peer.OpCustom(1, dic, true);}}private void OnDestroy() {//断开连接peer.Disconnect(); }public void DebugReturn(DebugLevel level, string message){}/// <summary>/// 接收服务器事件/// </summary>/// <param name="eventData"></param>public void OnEvent(EventData eventData){if(eventData.Code == 1) {Debug.Log("事件" + eventData.Parameters[1]);}}/// <summary>/// 接收服务器响应/// </summary>/// <param name="operationResponse"></param>public void OnOperationResponse(OperationResponse operationResponse){if (operationResponse.OperationCode == 1){Debug.Log(operationResponse.Parameters[1]);}}/// <summary>/// 状态改变/// </summary>/// <param name="statusCode"></param>public void OnStatusChanged(StatusCode statusCode){Debug.Log(statusCode);}}
-  服务器 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Photon.SocketServer; using PhotonHostRuntimeInterfaces;namespace PhotonServerFirst {public class PSpeer : ClientPeer{public PSpeer(InitRequest initRequest) : base(initRequest){}//处理客户端断开的后续工作protected override void OnDisconnect(DisconnectReason reasonCode, string reasonDetail){throw new NotImplementedException();}//处理客户端的请求protected override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters){switch (operationRequest.OperationCode){case 1://收到Dictionary<byte, object> data = operationRequest.Parameters;PSTest.log.Info("收到客户端消息:" + data[1].ToString());//返回Dictionary<byte, object> data2 = new Dictionary<byte, object>();data2.Add(1, "你好,我是服务器");// OperationResponse operationResponse = new OperationResponse();// operationResponse.OperationCode = 1;// operationResponse.Parameters = data2;//创建一个响应OperationResponse operationResponse = new OperationResponse(1, data2);SendOperationResponse(operationResponse, sendParameters);//创建一个事件EventData Edata = new EventData(1, data2); SendEvent(Edata, sendParameters);break;default:break;}}} }
Dlc 出现vscode引用不好使的时候
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-E1OopesN-1691110946427)(../AppData/Roaming/Typora/typora-user-images/image-20230803224102512.png)]](https://img-blog.csdnimg.cn/7ef5044dd4ba46c396e745add1c405f2.png)
检查下这个。