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)
{
}
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);
}
}
public override void OnDestroy()
{
base.OnDestroy();
try
{
Debug.Log("已关闭与服务器的连接");
clientSocket.Close();
}
catch (Exception e)
{
Debug.LogError("无法关闭跟服务器的连接" + e);
}
}
public void SendRequest(RequestCode requestCode, ActionCode actionCode, string data)
{
byte[] bytes = Message.PackData(requestCode, actionCode, data);
clientSocket.Send(bytes);
}
private void Start()
{
clientSocket.BeginReceive(msg.Data, msg.StartIndex, msg.RemainSize, SocketFlags.None, ReceiveCallBack, null);
}
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);
}
}
private void OnProcessDataCallBack(ActionCode actionCode, string data)
{
gameManager.HandleReponse(actionCode, data);
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-53727.html