IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 游戏开发 -> photonServer学习记录(一) -> 正文阅读

[游戏开发]photonServer学习记录(一)

photonserver版本:4.0.28.2962
VS2019

一 . 启动PhotonServer
安装目录下找到PhotonConTrol.exe打开
请添加图片描述
桌面右下角出现photon图标

二 . 创建服务器端项目,并设置目录部署
1.打开vs新建解决方案 MyGameServer
2.修改目标框架为 .NET Framework 4.6.1 太高怕photon支持不了
3.在photon安装目录中找到deploy文件夹,新建MyGameServer/bin目录,设置VS输出路径到此目录

4.设置引用
在libs文件夹中找到这5个dll,
请添加图片描述
5.新建MyGameServerMain类继承ApplicationBase,实现接口,需要引入Photon.SocketServer;
新建ClientPeer,继承Photon.SocketServer.ClientPeer,实现接口
.点击生成dll
6.请添加图片描述
找到PhotonServer.config.用vs打开
添加配置
7.在configuration根下添加如下

	<!-- Instance settings -->
	<MyGameInstance <!-- 自定义Instance -->
		MaxMessageSize="512000"
		MaxQueuedDataPerPeer="512000"
		PerPeerMaxReliableDataInTransit="51200"
		PerPeerTransmitRateLimitKBSec="256"
		PerPeerTransmitRatePeriodMilliseconds="200"
		MinimumTimeout="5000"
		MaximumTimeout="30000"
		DisplayName="My Game"   <!-- 1.Photon中显示的名字 -->
		>

		<!-- 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="MyGame1"> <!-- 2.应用程序名 ,自定义 -->
			</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="MyGame1" <!-- 3.应用程序名 ,自定义 -->
				>
			</TCPListener>
		</TCPListeners>

	

		<!-- Defines the Photon Runtime Assembly to use. -->
		<Runtime
			Assembly="PhotonHostRuntime, Culture=neutral"
			Type="PhotonHostRuntime.PhotonDomainManager"
			UnhandledExceptionPolicy="Ignore">
		</Runtime>


		<!-- Defines which applications are loaded on start and which of them is used by default. Make sure the default application is defined. -->
		<!-- Application-folders must be located in the same folder as the bin_win32 folders. The BaseDirectory must include a "bin" folder. -->
		<Applications Default="MyGame1">  <!--应用程序名 ,自定义 -->

			<!-- MMO Demo Application -->
			<Application
				Name="MyGame1" <!-- 应用程序名 ,自定义 -->
				BaseDirectory="MyGameServer" <!-- 在deploy文件夹下应用程序所在的文件夹名称 -->
				Assembly="MyGameServer"<!-- 程序集名字 -->
				Type="MyGameServer.MyGameServerMain"<!-- 配置的主要的脚本 -->
				ForceAutoRestart="true"
				WatchFiles="dll;config"
				ExcludeFiles="log4net.config">
			</Application>

		

		</Applications>
	</MyGameInstance><!-- 自定义Instance -->

8.新建`MyGameServerMain作为主要脚本 ,具体内容


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

namespace MyGameServer
{
    public class MyGameServerMain : ApplicationBase
    {
        public  static readonly ILogger log = LogManager.GetCurrentClassLogger();   //日志输出对象 对日志进行输出
        //当一个客户端请求连接
        //我们使用peerbase,表示和一个客户端的连接
        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"));  //设置log4net.config 的配置 路径  BinaryPath表示相对路径
            if (configFileInfo.Exists )
            {
                LogManager.SetLoggerFactory(Log4NetLoggerFactory.Instance);//设置使用哪个日志插件
                XmlConfigurator.ConfigureAndWatch(configFileInfo);//让log4net读取配置文件
            }

            log.Info(" Set Log4 ok !");
        }
        //服务器关闭
        protected override void TearDown()
        {
            log.Info("服务器应用关闭了");
        }
    }
}

9.新建clientpeer具体如下

using Photon.SocketServer;
using PhotonHostRuntimeInterfaces;
using System.Collections.Generic;

namespace MyGameServer
{
    public 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) //通过code区分请求
            {
                case 1:
                    MyGameServerMain.log.Info("收到了一个客户端的请求  ");

                    OperationResponse operation = new OperationResponse(1);
                    Dictionary<byte, object> data = operationRequest.Parameters;
                    object  x;
                    data.TryGetValue( 1,out x);
                    object y;
                    data.TryGetValue(2, out y);
                    MyGameServerMain.log.Info("得到的参数数据是 : " + x .ToString ()+ "     +   " + y.ToString ());


                    Dictionary<byte, object> data2 = new Dictionary<byte, object>();
                    data2.Add(1, 2020);
                    data2.Add(2, "回复你消息");
                    operation.SetParameters(data2);

                    SendOperationResponse(operation, sendParameters);//给客户端回消息

                    //发送事件
                    EventData eventData = new EventData(1);
                    eventData.Parameters = data2;
                    SendEvent(eventData, new SendParameters());
                    break;
                case 2:
                    break;
                default:
                    break;
            }
        }
    }
}

10.配置log4gnet.config请添加图片描述
找到log4gnet.config.xml 复制到MyGameServer下请添加图片描述
修改输出的日志文本文档名 为MyGameLog4

二.新建Unity项目
1.新建Plugins 文件夹
在libs文件夹中找到Photon3Unity3D.dll导入
2.新建unity脚本

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

public class PhotonEngine : MonoBehaviour,IPhotonPeerListener 
{
    public static PhotonEngine Instance = null;

    private static  PhotonPeer peer;

    public static PhotonPeer Peer
    {
        get { return peer; }
    }

    //向服务端发送错误日志
    public void DebugReturn(DebugLevel level, string message)
    {
        throw new System.NotImplementedException();
    }

    //接收服务端的事件
    public void OnEvent(EventData eventData)
    {
        switch (eventData.Code )
        {
            case 1:
                Debug.Log("收到客户端发来的一个事件");
                Dictionary<byte, object> data = eventData.Parameters;
                object x;
                data.TryGetValue(1, out x);
                object y;
                data.TryGetValue(2, out y);

                Debug.Log(x.ToString() + y.ToString());
                break;
            default:
                break;
        }
    }

    //接受服务端的回应
    public void OnOperationResponse(OperationResponse operationResponse)
    {
        switch (operationResponse .OperationCode )
        {
            case 1:
                Debug.Log("收到客户端的回复");
                Dictionary<byte, object> data = operationResponse.Parameters;

                object x;
                data.TryGetValue(1, out x);
                object y;
                data.TryGetValue(2, out y);

                Debug.Log(x.ToString() + y.ToString());

                break;
        }
    }

    //连接状态改变
    public void OnStatusChanged(StatusCode statusCode)
    {
        Debug.Log(statusCode);
    }

    private void Awake()
    {
        Instance = this;
    }

    private void Start()
    {
        //通过Listener接受服务器的响应
         peer = new PhotonPeer(this, ConnectionProtocol.Udp);
        peer.Connect("127.0.0.1:5055","MyGame1");
    }

    private void Update()
    {
      
        peer.Service();       


    }

    private void OnDestroy()
    {
        if (peer!=null &&peer .PeerState ==PeerStateValue.Connected )
        {
            peer.Disconnect();
        }
    }
}

新建test脚本

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{

    void Update()
    {
        if (Input .GetKeyDown (KeyCode.Space))
        {
            SendRequset();
        }
    }

    private void SendRequset()
    {
        Debug.Log("向服务器端发送了一条请求");
        Dictionary<byte, object> data = new Dictionary<byte, object>();
        data.Add(1, 100);
        data.Add(2, "传送数据");

        PhotonEngine.Peer.OpCustom(1 ,data ,true );
    }
}

三.测试
服务器启动
打开log日志
启动服务器
启动unity请添加图片描述
测试成功

  游戏开发 最新文章
6、英飞凌-AURIX-TC3XX: PWM实验之使用 GT
泛型自动装箱
CubeMax添加Rtthread操作系统 组件STM32F10
python多线程编程:如何优雅地关闭线程
数据类型隐式转换导致的阻塞
WebAPi实现多文件上传,并附带参数
from origin ‘null‘ has been blocked by
UE4 蓝图调用C++函数(附带项目工程)
Unity学习笔记(一)结构体的简单理解与应用
【Memory As a Programming Concept in C a
上一篇文章      下一篇文章      查看所有文章
加:2021-07-23 11:09:28  更:2021-07-23 11:11:20 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/5 1:09:23-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码