using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
public class NewtworkManager : MonoBehaviour
{
private int index;
private Socket sock;
private object socketDataArrival;
private object socketDisconnected;
///
/// 异步连接
///
///
///
public void AsyncSocket(Socket sock, int index)
{
this.index = index;
this.sock = sock;
this.SetHeartBeat(this.sock);
Socket obj_Socket = sock;
StateObject obj_SocketState = new StateObject();
obj_SocketState.workSocket = obj_Socket;
obj_Socket.BeginReceive(obj_SocketState.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), obj_SocketState);
}
//设置心跳
private void SetHeartBeat(Socket tmpsock)
{
byte[] inValue = new byte[] { 1, 0, 0, 0, 0x20, 0x4e, 0, 0, 0xd0, 0x07, 0, 0 };// 首次探测时间20 秒, 间隔侦测时间2 秒
tmpsock.IOControl(IOControlCode.KeepAliveValues, inValue, null);
}
///
/// 异步连接的回调函数
///
///
private void ReceiveCallback(IAsyncResult ar)
{
try
{
StateObject obj_SocketState = (StateObject)ar.AsyncState;
Socket obj_Socket = obj_SocketState.workSocket;
int BytesRead = obj_Socket.EndReceive(ar);
if (BytesRead > 0)
{
byte[] tmp = new byte[BytesRead];
Array.ConstrainedCopy(obj_SocketState.buffer, 0, tmp, 0, BytesRead);
if (socketDataArrival != null)
{
SocketDataArrival(this.index, tmp);
}
}
else
{
if (this.sock.Connected)
{
if (socketDisconnected != null)
{
SocketDisconnected(index);
}
}
}
obj_Socket.BeginReceive(obj_SocketState.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), obj_SocketState);
}
catch (Exception ex)
{
if (socketDisconnected != null)
{
SocketDisconnected(index); //Keepalive检测断线引发的异常在这里捕获
}
}
}
private void SocketDisconnected(int index)
{
throw new NotImplementedException();
}
private void SocketDataArrival(int index, byte[] tmp)
{
throw new NotImplementedException();
}
}
public class StateObject
{
public Socket worksocket = null;
public const int buffersize = 1024;
public byte[] buffer = new byte[buffersize];
// public byte[] sendbuffer=new byte[buffersize];
public StringBuilder sb = new StringBuilder();
public StateObject()
{
}
}