Unity Advanced--PhotonServer를 사용하여 서버와 클라이언트 간의 통신 실현--PhotonServer (1)

Unity Advanced – PhotonServer를 사용하여 서버 및 클라이언트 통신 구현

서버 설치 및 구성

Photon 주소: https://www.photonengine.com/zh-cn/sdks

  • 해당 SDK를 다운로드합니다.

[외부링크 이미지 전송에 실패했습니다. 원본 사이트에 리칭 방지 메커니즘이 있을 수 있습니다. 이미지를 저장하고 직접 업로드하는 것을 권장합니다. (img-nqhFg3FR-1691110946416) (../AppData/Roaming/Typora/typora-user -이미지/이미지-20230802150527693.png)]

  • Visual Studio에서 새 클래스 라이브러리를 만듭니다.

**[외부 링크 이미지 전송에 실패했습니다. 원본 사이트에 리칭 방지 메커니즘이 있을 수 있습니다. 이미지를 저장하고 직접 업로드하는 것이 좋습니다. (img-YNC7wHVC-1691110946416)(../AppData/Roaming/Typora/typora- 사용자-이미지/이미지- 20230802151715763.png)]**

프로젝트에 해당 dll 파일 참조를 추가합니다.

[외부 링크 이미지 전송에 실패했습니다. 원본 사이트에 리치 방지 메커니즘이 있을 수 있습니다. 이미지를 저장하고 직접 업로드하는 것을 권장합니다. (img-SfcLhTkB-1691110946417)(../AppData/Roaming/Typora/typora-user -이미지/이미지-20230802160144216.png)]

이 폴더에서 찾으세요:

[외부 링크 이미지 전송에 실패했습니다. 원본 사이트에 리치 방지 메커니즘이 있을 수 있습니다. 이미지를 저장하고 직접 업로드하는 것을 권장합니다. (img-v58YvXYT-1691110946417)(../AppData/Roaming/Typora/typora-user -이미지/이미지-20230802175928178.png)]

다섯 가지 플러그인은 다음과 같습니다.

[외부링크 이미지 전송에 실패했습니다. 원본 사이트에 리치 방지 메커니즘이 있을 수 있습니다. 이미지를 저장하고 직접 업로드하는 것을 권장합니다. (img-XdLbRv77-1691110946417) (../AppData/Roaming/Typora/typora-user -이미지/이미지-20230802160856827.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 -이미지/이미지-20230802152237347.png)]

  • 빌드 디렉터리를 수정합니다.

[외부 링크 이미지 전송에 실패했습니다. 원본 사이트에 리치 방지 메커니즘이 있을 수 있습니다. 이미지를 저장하고 직접 업로드하는 것을 권장합니다. (img-OZs48M4L-1691110946418)(../AppData/Roaming/Typora/typora-user -이미지/이미지-20230802182536425.png)]

[외부 링크 이미지 전송에 실패했습니다. 원본 사이트에 리치 방지 메커니즘이 있을 수 있습니다. 이미지를 저장하고 직접 업로드하는 것을 권장합니다. (img-Dvn72gRd-1691110946418)(../AppData/Roaming/Typora/typora-user -이미지/이미지-20230802182941475.png)]

이전에 만든 저장소에 넣으세요.

그런 다음 생성하십시오.

  • PhotonServer 구성 파일 수정

[외부 링크 이미지 전송 실패, 소스 사이트에 안티 리칭 메커니즘이 있을 수 있습니다. 이미지를 저장하고 직접 업로드하는 것이 좋습니다. (img-H5BLT0QY-1691110946420)(../AppData/Roaming/Typora/typora-user -이미지/이미지-20230803090947410 .png)]
찾고 있는

[외부링크 이미지 전송에 실패했습니다. 원본 사이트에 리칭 방지 메커니즘이 있을 수 있습니다. 이미지를 저장하고 직접 업로드하는 것을 권장합니다. (img-PpBI5krl-1691110946424) (../AppData/Roaming/Typora/typora-user -이미지/이미지-20230803091005322.png)]

  • 구성 파일:

         <!-- DisplayName:显示名称 -->
    	<PhotonServerFirst
    		MaxMessageSize="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>
    			<UDPListener
    				IPAddress="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>
    			<TCPListener
    				IPAddress="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. -->
    		<Runtime
    			Assembly="PhotonHostRuntime, Culture=neutral"
    			Type="PhotonHostRuntime.PhotonDomainManager"
    			UnhandledExceptionPolicy="Ignore">
    		</Runtime>
    				
    		<Applications Default="PhotonServerFirst">
    		
    			<!-- Name:要注意和上面填写的应用名字相同 -->
    			<!--BaseDirectory:编译好的dll所在文件夹名-->
    		    <!--Assembly:dll名-->
    		    <!--Type:命名空间.类名-->
    			<Application
    				Name="PhotonServerFirst"
    				BaseDirectory="PhotonServerFirst"
    				Assembly="PhotonServerFirst"
    				Type="PhotonServerFirst.PSTest"
    				ForceAutoRestart="true"
    				WatchFiles="dll;config"
    				ExcludeFiles="log4net.config">
    			</Application>
    
    		</Applications>
    	</PhotonServerFirst>
    

    이러한 방식으로 우리가 만든 서버는 photonServer에서 사용할 수 있습니다.

로그 추가

  1. [외부 링크 이미지 전송에 실패했습니다. 원본 사이트에 리치 방지 메커니즘이 있을 수 있습니다. 이미지를 저장하고 직접 업로드하는 것을 권장합니다. (img-ocfdDxLc-1691110946425)(../AppData/Roaming/Typora/typora-user -images/image-20230803092647288.png)]
    아래를 보고 프로젝트 log4net.config에 복사하세요.

  2. 그런 다음 속성을 항상 복사하도록 변경하십시오.

    [외부 링크 이미지 전송에 실패했습니다. 원본 사이트에 리치 방지 메커니즘이 있을 수 있습니다. 이미지를 저장하고 직접 업로드하는 것을 권장합니다. (img-wJQkJxCi-1691110946427)(../AppData/Roaming/Typora/typora-user -images/image-20230803092916486.png)]

  3. 출력 로그의 이름 변경

    <file type="log4net.Util.PatternString" value="%property{Photon:ApplicationLogPath}\\PhotonServerFirst.Server.log" />
    
  4. 서버 프로그램 구성

    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设置日志为log4net
                    LogManager.SetLoggerFactory(Log4NetLoggerFactory.Instance);
                    XmlConfigurator.ConfigureAndWatch(configFileInfo);
                    log.Info("初始化成功");
                }
            }
            #endregion        
            
        }
    }
    
    
  5. Photonserver를 열어 애플리케이션을 실행하면 로그 출력이 성공적으로 구성됩니다.

클라이언트 구성

  1. 아래에서Photon-OnPremise-Server-SDK_v4-0-29-11263 > lib > 찾아서 Photon3Unity3D.dllunity3d의 플러그인 폴더(Pluigins)에 넣어주세요.
  2. 삭제되지 않는 싱글톤 구성 요소에 바인딩할 클라이언트 스크립트를 작성합니다. (코드는 아래와 같습니다)

클라이언트와 서버 간의 통신

  • 고객

    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 update
        void 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;
                }
            }
        }
    }
    
    

vscode 참조가 작동하지 않을 때 Dlc가 나타납니다.

[외부 링크 이미지 전송에 실패했습니다. 원본 사이트에 리치 방지 메커니즘이 있을 수 있습니다. 이미지를 저장하고 직접 업로드하는 것을 권장합니다. (img-E1OopesN-1691110946427)(../AppData/Roaming/Typora/typora-user -이미지/이미지-20230803224102512.png)]

이것 좀 봐.

추천

출처blog.csdn.net/abaidaye/article/details/132096415