PhotonServer-服务端给客户端的Event推送

1.服务端向客户端推送Event

完整代码:

ClientPeer.cs:

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

namespace RRGameServer
{
    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);
                    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);
                    ed.Parameters = data2;
                    SendEvent(ed, new SendParameters());
                    break;
                default:
                    break;
            }
        }
    }
}

2.客户端接收Event

 完整代码

PhotonEngine.cs:

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

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

   

    public static PhotonPeer peer;
    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            //当前Gameobject不会随场景的销毁而销毁
            DontDestroyOnLoad(this.gameObject);
        }
    }

    void Start () {
        peer = new PhotonPeer(this,ConnectionProtocol.Udp);
        peer.Connect("127.0.0.1:5055", "MyGame6");//通过ip连接到到对应的我们config中配置的Allpication
	}
	
	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:
                //解析数据
                var data = eventData.Parameters;
                object intValue, StringValue;
                data.TryGetValue(1, out intValue);
                data.TryGetValue(2, out StringValue);
                Debug.Log("收到服务器的响应Event推送,OpCode:1" + intValue.ToString() + ":" + StringValue.ToString());
                break;
            default:
                break;
        }
    }

    public void OnOperationResponse(OperationResponse operationResponse)
    {
        //DicTool.GetValue(RequestDic, (OperationCode)operationResponse.OperationCode).
        //    OnOprationRespionse(operationResponse);

        //return;
        switch (operationResponse.OperationCode)
        {
            case 1:
                Debug.Log("收到服务器的响应,OpCode:1");

                //解析数据
                var data = operationResponse.Parameters;
                object intValue;
                data.TryGetValue(1, out intValue);
                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);
    }

    //private Dictionary<OperationCode, Request> RequestDic = new Dictionary<OperationCode, Request>();

    public void AddRequest(Request r)
    {
        //RequestDic.Add(r.OpCode, r);
    }
    public void RemoveRequest(Request r)
    {
       // RequestDic.Remove(r.OpCode);
    }
}

效果:

 

要在 Netty 中实现 WebSocket 服务端主动向客户端推送消息,可以使用 `ChannelGroup` 来管理连接到服务器的 WebSocket 客户端的 `Channel`,然后通过遍历 `ChannelGroup` 并将消息写入每个 `Channel` 来实现消息的推送。 下面是一个示例代码,演示了如何在 Netty 中实现 WebSocket 服务端主动向客户端推送消息: ```java public class WebSocketServerHandler extends SimpleChannelInboundHandler<WebSocketFrame> { private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); @Override protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception { // 处理 WebSocket 请求 if (frame instanceof TextWebSocketFrame) { // 处理文本消息 String text = ((TextWebSocketFrame) frame).text(); System.out.println("Received message: " + text); // 推送消息给所有连接的客户端 channelGroup.writeAndFlush(new TextWebSocketFrame("Server: " + text)); } else { // 其他类型的消息,如二进制消息、Ping/Pong 消息等 // ... } } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { // 当有客户端连接时,将其添加到 ChannelGroup 中 Channel channel = ctx.channel(); channelGroup.add(channel); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { // 当有客户端断开连接时,将其从 ChannelGroup 中移除 Channel channel = ctx.channel(); channelGroup.remove(channel); } // 主动向客户端推送消息的方法 public void pushMessageToClients(String message) { channelGroup.writeAndFlush(new TextWebSocketFrame("Server: " + message)); } } ``` 在上述示例中,我们创建了一个静态的 `ChannelGroup` 对象 `channelGroup`,用于存储连接到服务器的 WebSocket 客户端的 `Channel`。当有客户端连接时,将其添加到 `channelGroup` 中;当客户端断开连接时,将其从 `channelGroup` 中移除。 在处理 WebSocket 请求时,如果收到文本消息,我们可以通过调用 `channelGroup.writeAndFlush()` 方法将消息写入每个客户端的 `Channel` 中,实现消息的推送。 此外,我们还添加了一个名为 `pushMessageToClients()` 的方法,用于在服务端主动向所有客户端推送消息。 你可以在适当的时候调用 `pushMessageToClients()` 方法来推送消息给所有连接的客户端。例如,可以在定时任务或其他事件触发的地方调用该方法来主动向客户端推送消息。 希望对你有所帮助!如果还有其他问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值