//==========================
// - FileName: ClientManager.cs
// - Created: true.
// - CreateTime: 2020/06/25 23:46:44
// - Email: 1670328571@qq.com
// - Region: China WUHAN
// - Description: 管理服务器端的 Socket 连接
//==========================
using ShareProject;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;
public class ClientManager:BaseManager
{
private Socket clientSocket;
//数据存储以及解析
private Message msg = new Message();
public ClientManager(GameManager gameManager) : base(gameManager)
{
}
/// <summary>
/// 建立连接
/// </summary>
public override void OnInit()
{
base.OnInit();
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
//建立连接
clientSocket.Connect(StringManager.IP, StringManager.PORT);
Debug.Log("连接服务器成功");
Start();
}
catch (Exception e)
{
Debug.LogError("服务器未开启..." + e);
//Debug.Log("无法连接到服务器端:" + e);
}
}
/// <summary>
/// 关闭连接
/// </summary>
public override void OnDestroy()
{
base.OnDestroy();
//判断是否为 null
try
{
Debug.Log("已关闭与服务器的连接");
clientSocket.Close();
}
catch (Exception e)
{
Debug.LogError("无法关闭跟服务器的连接" + e);
}
}
/// <summary>
/// 发送请求
/// </summary>
/// <param name="requestCode"></param>
/// <param name="actionCode"></param>
/// <param name="data"></param>
public void SendRequest(RequestCode requestCode, ActionCode actionCode, string data)
{
//打包
byte[] bytes = Message.PackData(requestCode, actionCode, data);
//发送
clientSocket.Send(bytes);
}
/// <summary>
/// 开始接收
/// </summary>
private void Start()
{
//异步消息接收
clientSocket.BeginReceive(msg.Data, msg.StartIndex, msg.RemainSize, SocketFlags.None, ReceiveCallBack, null);
}
/// <summary>
/// 异步接收
/// </summary>
/// <param name="ar"></param>
private void ReceiveCallBack(IAsyncResult ar)
{
try
{
if (clientSocket == null || clientSocket.Connected == false)
{
return;
}
//接收的数据
int count = clientSocket.EndReceive(ar);
msg.ReadMessage(count, OnProcessDataCallBack);
//消息的处理
//继续监听
Start();
}
catch (Exception e)
{
Debug.LogError("与服务器断开连接..." + e);
}
}
/// <summary>
/// 回调函数
/// </summary>
/// <param name="actionCode"></param>
/// <param name="data"></param>
private void OnProcessDataCallBack(ActionCode actionCode, string data)
{
gameManager.HandleReponse(actionCode, data);
}
}
Manager Of Managers(六)ClientManager
最新推荐文章于 2023-01-04 17:35:48 发布