TaidouChatServerClient(客户端)

本文介绍如何使用Photon库实现客户端与服务器之间的实时通讯,包括连接服务器、发送接收消息及响应处理等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*需添加引用:"ExitGamesLibs.dll" "Photon.SocketServer.dll" "PhotonHostRuntimeInterfaces.dll"" Photon3DotNet.dll"*/




using ExitGames.Client.Photon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace TaidouChatServerClient  
{


    class ChatServerListener : IPhotonPeerListener  //实现 接口IPhotonPeerListener
    {
        public bool isConnected = false;
      //进行一些Debug的回掉和Debug的输出 日志的输出
        public void DebugReturn(DebugLevel level, string message)
        {


        }

    //服务器端进行回应时,服务器端进行调用的  OnEvent和OnOperationResponse
        public void OnEvent(EventData eventData)
        {


        }


        public void OnMessage(object messages)
        {


        } 


        //得到服务器端的响应
        public void OnOperationResponse(OperationResponse operationResponse)
        {
            Dictionary<byte, object> dict = operationResponse.Parameters;//.Parameters就是我们的字典参数
            object v = null;
            dict.TryGetValue(1, out v);
            Console.WriteLine("Get value from server:" + v.ToString());
        }

    //表示客户端和服务器端连接状态发生变化时 调用的
        public void OnStatusChanged(StatusCode statusCode)
        {
            Console.WriteLine(statusCode);
            switch (statusCode)
            {
                case StatusCode.Connect:
                    isConnected = true;
                    Console.WriteLine("Connect .");
                    break;
            }
        }
    }


//用peer向服务器端发起请求,用ChatServerListener(也就是listener)去响应服务器端的请求

    class Program
    {
        static void Main(string[] args)
        {
            ChatServerListener listener = new ChatServerListener();  创建一个监听器listener
            PhotonPeer peer = new PhotonPeer(listener, ConnectionProtocol.Tcp); /*利用PhotonPeer与服务器端进行交互     监听类是用来监听服务器返回的一些方法,返回的一些消息的,需要一个IPhotonPeerListener,所以创建一个监听类ChatServerListener 实现接口IPhotonPeerListener*/
            peer.Connect("127.0.0.1:4530", "ChatServer");//连接服务器,需要时间
            Console.WriteLine("Connecting ... ");
            while (listener.isConnected == false)
                peer.Service();  //向服务器发起请求
            Dictionary<byte, object> dict = new Dictionary<byte, object>();
            dict.Add(1, "username");
            dict.Add(2, "password");
            peer.OpCustom(1, dict, true);//OpCustom用来向服务器端发起一个请求    true表示发起的请求可靠  
//需要一些时间,故后边不能立即跟peer.Service();


            while (true)
            {
                peer.Service();
            }


        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值