add
This commit is contained in:
179
Assets/CoolapeFrame/Scripts/net/Net.cs
Normal file
179
Assets/CoolapeFrame/Scripts/net/Net.cs
Normal file
@@ -0,0 +1,179 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using XLua;
|
||||
|
||||
|
||||
namespace Coolape
|
||||
{
|
||||
#if !UNITY_WEBGL
|
||||
public class Net : Tcp
|
||||
{
|
||||
public static Net self;
|
||||
|
||||
public Net()
|
||||
{
|
||||
self = this;
|
||||
}
|
||||
public CLBaseLua lua;
|
||||
public LuaTable luaTable = null;
|
||||
public enum NetWorkType
|
||||
{
|
||||
publish,
|
||||
test1,
|
||||
test2,
|
||||
}
|
||||
|
||||
public int _SuccessCodeValue = 1;
|
||||
|
||||
// 成功的返回值
|
||||
public static int SuccessCode
|
||||
{
|
||||
get
|
||||
{
|
||||
return self._SuccessCodeValue;
|
||||
}
|
||||
}
|
||||
|
||||
[HideInInspector]
|
||||
public NetWorkType switchNetType = NetWorkType.publish;
|
||||
[HideInInspector]
|
||||
public string host4Publish = "";
|
||||
[HideInInspector]
|
||||
public string host4Test1 = "";
|
||||
[HideInInspector]
|
||||
public string host4Test2 = "";
|
||||
|
||||
public string serializeluaPath = "";
|
||||
|
||||
// 默认地址
|
||||
string _gateHost;
|
||||
|
||||
public string gateHost
|
||||
{ //网关
|
||||
get
|
||||
{
|
||||
switch (switchNetType)
|
||||
{
|
||||
case NetWorkType.publish:
|
||||
_gateHost = host4Publish;
|
||||
break;
|
||||
case NetWorkType.test1:
|
||||
_gateHost = host4Test1;
|
||||
break;
|
||||
case NetWorkType.test2:
|
||||
_gateHost = host4Test2;
|
||||
break;
|
||||
}
|
||||
return _gateHost;
|
||||
}
|
||||
set
|
||||
{
|
||||
_gateHost = value;
|
||||
}
|
||||
}
|
||||
|
||||
//网关
|
||||
public int gatePort;
|
||||
|
||||
[XLua.CSharpCallLua]
|
||||
public delegate void __DispatchGame(object data);
|
||||
__DispatchGame dispatchGame;
|
||||
[XLua.CSharpCallLua]
|
||||
public delegate void TcpPackMessageAndSendFunc(object obj, Tcp tcp);
|
||||
TcpPackMessageAndSendFunc packMsgFunc;
|
||||
[XLua.CSharpCallLua]
|
||||
public delegate object TcpUnpackMessageFunc(MemoryStream buffer, Tcp tcp);
|
||||
TcpUnpackMessageFunc unPackMsgFunc;
|
||||
//=====================begain===================
|
||||
public void setLua()
|
||||
{
|
||||
lua.setLua();
|
||||
dispatchGame = lua.luaTable.GetInPath<__DispatchGame>("dispatchGame");
|
||||
initSerializeFunc();
|
||||
}
|
||||
|
||||
public void initSerializeFunc()
|
||||
{
|
||||
LuaEnv serializelua = null;
|
||||
if (serializeInMainThread) {
|
||||
serializelua = lua.lua;
|
||||
} else {
|
||||
serializelua = new LuaEnv();
|
||||
}
|
||||
CLUtlLua.addLuaLoader(serializelua);
|
||||
object[] ret = CLUtlLua.doLua (serializelua, serializeluaPath);
|
||||
if (ret != null && ret.Length > 0) {
|
||||
luaTable = (LuaTable)(ret [0]);
|
||||
packMsgFunc = luaTable.GetInPath<TcpPackMessageAndSendFunc>("packMsg");
|
||||
unPackMsgFunc = luaTable.GetInPath<TcpUnpackMessageFunc>("unpackMsg");
|
||||
} else {
|
||||
Debug.LogError("SetLua no luatable returned !! ==" + serializeluaPath);
|
||||
}
|
||||
}
|
||||
|
||||
//===================end=====================
|
||||
public void connect(string host, int port)
|
||||
{
|
||||
StartCoroutine(doConnect(host, port));
|
||||
}
|
||||
|
||||
IEnumerator doConnect(string host, int port)
|
||||
{
|
||||
yield return null;
|
||||
init(host, port, (TcpDispatchDelegate)dispatchData);
|
||||
base.connect();
|
||||
}
|
||||
|
||||
public void dispatchData(object data, Tcp tcp)
|
||||
{
|
||||
if (serializeInMainThread)
|
||||
{
|
||||
if (dispatchGame != null)
|
||||
{
|
||||
dispatchGame(data);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
msgQueue.Enqueue(data);
|
||||
}
|
||||
}
|
||||
|
||||
public override byte[] encodeData(object obj)
|
||||
{
|
||||
packMsgFunc(obj, this);
|
||||
return null;
|
||||
}
|
||||
|
||||
public override object parseRecivedData(MemoryStream buffer)
|
||||
{
|
||||
return unPackMsgFunc(buffer, this);
|
||||
}
|
||||
|
||||
Queue msgQueue = new Queue();
|
||||
public override void Update()
|
||||
{
|
||||
base.Update();
|
||||
if(msgQueue.Count > 0)
|
||||
{
|
||||
dispatchGame(msgQueue.Dequeue());
|
||||
}
|
||||
}
|
||||
|
||||
public void clean()
|
||||
{
|
||||
if(luaTable != null)
|
||||
{
|
||||
luaTable.Dispose();
|
||||
luaTable = null;
|
||||
}
|
||||
if(lua != null)
|
||||
{
|
||||
lua.destoryLua();
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
8
Assets/CoolapeFrame/Scripts/net/Net.cs.meta
Normal file
8
Assets/CoolapeFrame/Scripts/net/Net.cs.meta
Normal file
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fc6881a86a54f4d9e92abfc2fd1a3e4d
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
365
Assets/CoolapeFrame/Scripts/net/Tcp.cs
Normal file
365
Assets/CoolapeFrame/Scripts/net/Tcp.cs
Normal file
@@ -0,0 +1,365 @@
|
||||
/*
|
||||
********************************************************************************
|
||||
*Copyright(C),coolae.net
|
||||
*Author: chenbin
|
||||
*Version: 2.0
|
||||
*Date: 2017-01-09
|
||||
*Description: tcp
|
||||
*Others:
|
||||
*History:
|
||||
*********************************************************************************
|
||||
*/
|
||||
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System.IO;
|
||||
using XLua;
|
||||
|
||||
namespace Coolape
|
||||
{
|
||||
#if !UNITY_WEBGL
|
||||
public delegate void TcpDispatchDelegate(object data, Tcp tcp);
|
||||
public class Tcp : MonoBehaviour
|
||||
{
|
||||
public string host;
|
||||
public int port;
|
||||
public bool connected = false;
|
||||
public bool serializeInMainThread = true;
|
||||
//是否连接
|
||||
public bool isStopping = false;
|
||||
const int MaxReConnectTimes = 0;
|
||||
public static int __maxLen = 1024 * 1024;
|
||||
|
||||
System.Threading.Timer timer;
|
||||
public USocket socket;
|
||||
int reConnectTimes = 0;
|
||||
public const string CONST_Connect = "connectCallback";
|
||||
public const string CONST_OutofNetConnect = "outofNetConnect";
|
||||
TcpDispatchDelegate mDispatcher;
|
||||
byte[] tmpBuffer = new byte[__maxLen];
|
||||
|
||||
public virtual void init(string host, int port)
|
||||
{
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Init the specified host, port and dispatcher.
|
||||
/// </summary>
|
||||
/// <param name="host">Host.</param>
|
||||
/// <param name="port">Port.</param>
|
||||
/// <param name="dispatcher">Dispatcher,当接收到数据并解析成功后将调用该方法.</param>
|
||||
public virtual void init(string host, int port, TcpDispatchDelegate dispatcher)
|
||||
{
|
||||
mDispatcher = dispatcher;
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public void connect()
|
||||
{
|
||||
connect(null);
|
||||
}
|
||||
public void connect(object obj)
|
||||
{
|
||||
if (socket != null)
|
||||
{
|
||||
stop();
|
||||
}
|
||||
isStopping = false;
|
||||
socket = new USocket(host, port);
|
||||
|
||||
#if UNITY_EDITOR
|
||||
Debug.Log("connect ==" + host + ":" + port);
|
||||
#endif
|
||||
//异步连接
|
||||
socket.connectAsync(onConnectStateChg);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ons the connect state chg. 当连接状态发生变化时
|
||||
/// </summary>
|
||||
/// <param name="s">S.</param>
|
||||
/// <param name="result">Result. 其实是bool类型,
|
||||
/// 当为true表示连接成功,false时表示没有连接成功或连接断开</param>
|
||||
public virtual void onConnectStateChg(USocket s, object result)
|
||||
{
|
||||
ArrayList list = result as ArrayList;
|
||||
bool isConnected = (bool)list[0];
|
||||
int retCode = (int)list[1];
|
||||
string msg = (string)list[2];
|
||||
if (isConnected)
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
Debug.Log("connectCallback success");
|
||||
#endif
|
||||
connected = true;
|
||||
reConnectTimes = 0;
|
||||
socket.ReceiveAsync(onReceive);
|
||||
enqueueData(CONST_Connect);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogWarning("connectCallback fail" + host + ":" + port + "," + isStopping);
|
||||
connected = false;
|
||||
if (!isStopping)
|
||||
{
|
||||
outofNetConnect(retCode, msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void outofNetConnect(int code, string msg)
|
||||
{
|
||||
if (isStopping)
|
||||
return;
|
||||
if (reConnectTimes < MaxReConnectTimes)
|
||||
{
|
||||
reConnectTimes++;
|
||||
Debug.LogWarning("reconnect times=" + reConnectTimes);
|
||||
if (timer != null)
|
||||
{
|
||||
timer.Dispose();
|
||||
}
|
||||
timer = TimerEx.schedule(connect, null, 5000);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (timer != null)
|
||||
{
|
||||
timer.Dispose();
|
||||
}
|
||||
timer = null;
|
||||
outofLine(socket, null);
|
||||
}
|
||||
}
|
||||
|
||||
public void outofLine(USocket s, object obj)
|
||||
{
|
||||
if (!isStopping)
|
||||
{
|
||||
stop();
|
||||
//CLMainBase.self.onOffline();
|
||||
enqueueData(CONST_OutofNetConnect);
|
||||
}
|
||||
}
|
||||
|
||||
public virtual void stop()
|
||||
{
|
||||
isStopping = true;
|
||||
connected = false;
|
||||
if (socket != null)
|
||||
{
|
||||
socket.close();
|
||||
}
|
||||
socket = null;
|
||||
}
|
||||
|
||||
//==========================================
|
||||
public bool send(object obj)
|
||||
{
|
||||
if (socket == null)
|
||||
{
|
||||
Debug.LogWarning("Socket is null");
|
||||
return false;
|
||||
}
|
||||
object ret = packMessage(obj);
|
||||
if (isStopping || !connected)
|
||||
{
|
||||
Debug.LogWarning("isStopping =" + isStopping + "|| !connected=" + !connected);
|
||||
return false;
|
||||
}
|
||||
if (ret != null)
|
||||
{
|
||||
socket.SendAsync(ret as byte[]);
|
||||
}
|
||||
else
|
||||
{
|
||||
//这种情况可能是在组包的时候就已经发送了,还有种情况就是异常,不过其实不太可能异常,先不处理
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public object packMessage(object obj)
|
||||
{
|
||||
try
|
||||
{
|
||||
return encodeData(obj);
|
||||
}
|
||||
catch (System.Exception e)
|
||||
{
|
||||
Debug.LogError(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
MemoryStream os = new MemoryStream();
|
||||
MemoryStream os2 = new MemoryStream();
|
||||
|
||||
/// <summary>
|
||||
/// Encodes the data.数据组包准备发送
|
||||
/// </summary>
|
||||
/// <returns>The data.</returns>
|
||||
/// <param name="obj">Object.</param>
|
||||
public virtual byte[] encodeData(object obj)
|
||||
{
|
||||
os.Position = 0;
|
||||
os2.Position = 0;
|
||||
|
||||
B2OutputStream.writeObject(os, obj);
|
||||
int len = (int)os.Position;
|
||||
B2OutputStream.writeInt(os2, len);
|
||||
os2.Write(os.ToArray(), 0, len);
|
||||
int pos = (int)os2.Position;
|
||||
byte[] result = new byte[pos];
|
||||
os2.Position = 0;
|
||||
os2.Read(result, 0, pos);
|
||||
return result;
|
||||
}
|
||||
|
||||
//==========================================
|
||||
MemoryStreamPool memorystreamPool = new MemoryStreamPool();
|
||||
public void onReceive(USocket s, byte[] bytes, int len)
|
||||
{
|
||||
MemoryStream buffer = memorystreamPool.borrowObject();
|
||||
buffer.Write(bytes, 0, len);
|
||||
buffer.SetLength(len);
|
||||
enqueueData(buffer);
|
||||
}
|
||||
|
||||
object netData = null;
|
||||
MemoryStream memoryBuff = null;
|
||||
MemoryStream receivedBuffer = new MemoryStream();
|
||||
public IEnumerator wrapBuffer2Unpack()
|
||||
{
|
||||
yield return null;
|
||||
while (receivedDataQueue.Count > 0)
|
||||
{
|
||||
netData = receivedDataQueue.Dequeue();
|
||||
if (netData != null)
|
||||
{
|
||||
if (netData is string)
|
||||
{
|
||||
if (mDispatcher != null)
|
||||
{
|
||||
mDispatcher(netData, this);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
memoryBuff = netData as MemoryStream;
|
||||
receivedBuffer.Write(memoryBuff.ToArray(), 0, (int)(memoryBuff.Length));
|
||||
memorystreamPool.returnObject(memoryBuff);
|
||||
}
|
||||
}
|
||||
if (receivedBuffer.Length > 0)
|
||||
{
|
||||
receivedBuffer.SetLength(receivedBuffer.Position);
|
||||
unpackMsg(receivedBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
public void unpackMsg(MemoryStream buffer)
|
||||
{
|
||||
bool isLoop = true;
|
||||
object o = null;
|
||||
long usedLen = 0;
|
||||
while (isLoop)
|
||||
{
|
||||
long totalLen = buffer.Length;
|
||||
if (totalLen > 2)
|
||||
{
|
||||
usedLen = 0;
|
||||
o = parseRecivedData(buffer);
|
||||
usedLen = buffer.Position;
|
||||
if (usedLen > 0)
|
||||
{
|
||||
int leftLen = (int)(totalLen - usedLen);
|
||||
if (leftLen > 0)
|
||||
{
|
||||
buffer.Read(tmpBuffer, 0, leftLen);
|
||||
buffer.Position = 0;
|
||||
buffer.Write(tmpBuffer, 0, leftLen);
|
||||
buffer.SetLength(leftLen);
|
||||
}
|
||||
else
|
||||
{
|
||||
buffer.Position = 0;
|
||||
buffer.SetLength(0);
|
||||
isLoop = false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//buffer.Position = totalLen;
|
||||
isLoop = false;
|
||||
}
|
||||
|
||||
if (o != null && mDispatcher != null)
|
||||
{
|
||||
mDispatcher(o, this);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
isLoop = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses the recived data.解析接收的数据,解析成功后发送给dispatcher
|
||||
/// </summary>
|
||||
/// <returns>The recived data.</returns>
|
||||
/// <param name="buffer">Buffer.</param>
|
||||
public virtual object parseRecivedData(MemoryStream buffer)
|
||||
{
|
||||
object ret = null;
|
||||
long oldPos = buffer.Position;
|
||||
buffer.Position = 0;
|
||||
long tatolLen = buffer.Length;
|
||||
long needLen = B2InputStream.readInt(buffer);
|
||||
if (needLen <= 0 || needLen > __maxLen)
|
||||
{
|
||||
// 网络Number据错误。断isOpen网络
|
||||
outofLine(this.socket, false);
|
||||
//this.stop();
|
||||
return null;
|
||||
}
|
||||
long usedLen = buffer.Position;
|
||||
if (usedLen + needLen <= tatolLen)
|
||||
{
|
||||
ret = B2InputStream.readObject(buffer);
|
||||
}
|
||||
else
|
||||
{
|
||||
//说明长度不够
|
||||
buffer.Position = oldPos;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
//======================================================================
|
||||
//======================================================================
|
||||
//======================================================================
|
||||
public Queue receivedDataQueue = new Queue();
|
||||
|
||||
public void enqueueData(object obj)
|
||||
{
|
||||
receivedDataQueue.Enqueue(obj);
|
||||
if (!serializeInMainThread)
|
||||
{
|
||||
StartCoroutine(wrapBuffer2Unpack());
|
||||
}
|
||||
}
|
||||
|
||||
public virtual void Update()
|
||||
{
|
||||
if (serializeInMainThread && receivedDataQueue.Count > 0)
|
||||
{
|
||||
StartCoroutine(wrapBuffer2Unpack());
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
8
Assets/CoolapeFrame/Scripts/net/Tcp.cs.meta
Normal file
8
Assets/CoolapeFrame/Scripts/net/Tcp.cs.meta
Normal file
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 396fd9223bf5744228f5370cbfaf46f3
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
337
Assets/CoolapeFrame/Scripts/net/USocket.cs
Normal file
337
Assets/CoolapeFrame/Scripts/net/USocket.cs
Normal file
@@ -0,0 +1,337 @@
|
||||
/*
|
||||
********************************************************************************
|
||||
*Copyright(C),coolae.net
|
||||
*Author: chenbin
|
||||
*Version: 2.0
|
||||
*Date: 2017-01-09
|
||||
*Description: socke,封装c# socketNumber据传输协议
|
||||
*Others:
|
||||
*History:
|
||||
*********************************************************************************
|
||||
*/
|
||||
using UnityEngine;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Collections;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
namespace Coolape
|
||||
{
|
||||
#if !UNITY_WEBGL
|
||||
public delegate void NetCallback(USocket socket, object obj);
|
||||
public delegate void OnReceiveCallback(USocket socket, byte[] bytes, int len);
|
||||
|
||||
public class USocket
|
||||
{
|
||||
public string host;
|
||||
public int port;
|
||||
public Socket mSocket;
|
||||
public static int mTmpBufferSize = 64 * 1024;
|
||||
public byte[] mTmpBuffer = null;
|
||||
private IPEndPoint ipe;
|
||||
private NetCallback onConnectStateChgCallback;
|
||||
private OnReceiveCallback onReceiveCallback;
|
||||
private int failTimes = 0;
|
||||
private bool isClosed = false;
|
||||
public bool isActive = false;
|
||||
public Timer timeoutCheckTimer;
|
||||
public enum Errors
|
||||
{
|
||||
success = 0,
|
||||
connectTimeout = 1,
|
||||
IPEndPointIsNull = 2,
|
||||
connectFailed = 3,
|
||||
receivebytesLenError = 4,
|
||||
serverClosedConnection = 5,
|
||||
connectionIsClosed = 6,
|
||||
sendAsynException = 7,
|
||||
sendTimeout = 8,
|
||||
}
|
||||
|
||||
public USocket(string host, int port)
|
||||
{
|
||||
init(host, port);
|
||||
}
|
||||
|
||||
public void init(string host, int port)
|
||||
{
|
||||
isClosed = false;
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
IPAddress ip = null;
|
||||
try
|
||||
{
|
||||
// is ip xx.xx.xx.xx
|
||||
ip = IPAddress.Parse(host);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// may be is dns
|
||||
try
|
||||
{
|
||||
IPAddress[] address = Dns.GetHostAddresses(host);
|
||||
if (address.Length > 0)
|
||||
{
|
||||
ip = address[0];
|
||||
}
|
||||
}
|
||||
catch (Exception e2)
|
||||
{
|
||||
Debug.LogError(e2);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (ip == null)
|
||||
{
|
||||
Debug.LogError("Get ip is null");
|
||||
return;
|
||||
}
|
||||
ipe = new IPEndPoint(ip, port);
|
||||
|
||||
if (ip.AddressFamily == AddressFamily.InterNetworkV6)
|
||||
{
|
||||
Debug.LogWarning("is ipv6");
|
||||
mSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogWarning("is ipv4");
|
||||
mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
}
|
||||
|
||||
if (mTmpBuffer == null)
|
||||
{
|
||||
mTmpBuffer = new byte[mTmpBufferSize];
|
||||
}
|
||||
}
|
||||
|
||||
// 异步模式//////////////////////////////////////////////////////////////////
|
||||
// 异步模式//////////////////////////////////////////////////////////////////
|
||||
//public bool IsConnectionSuccessful = false;
|
||||
public int timeoutMSec = 5000; //毫秒
|
||||
public int maxTimeoutTimes = 3;
|
||||
Timer connectTimeout = null;
|
||||
|
||||
public void connectAsync(NetCallback onConnectStateChgCallback)
|
||||
{
|
||||
try
|
||||
{
|
||||
isActive = false;
|
||||
this.onConnectStateChgCallback = onConnectStateChgCallback;
|
||||
if (ipe == null)
|
||||
{
|
||||
onConnectStateChg(false, Errors.IPEndPointIsNull);
|
||||
return;
|
||||
}
|
||||
|
||||
mSocket.BeginConnect(ipe, (AsyncCallback)connectCallback, this);
|
||||
if (connectTimeout != null)
|
||||
{
|
||||
connectTimeout.Dispose();
|
||||
connectTimeout = null;
|
||||
}
|
||||
connectTimeout = TimerEx.schedule((TimerCallback)connectTimeOut, null, timeoutMSec);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.LogError(e);
|
||||
}
|
||||
}
|
||||
|
||||
void connectTimeOut(object orgs)
|
||||
{
|
||||
if (isActive)
|
||||
{
|
||||
}
|
||||
else
|
||||
{
|
||||
onConnectStateChg(false, Errors.connectTimeout);
|
||||
}
|
||||
}
|
||||
|
||||
protected void onConnectStateChg(bool connected, Errors retCode)
|
||||
{
|
||||
string msg = Enum.GetName(typeof(Errors), retCode);
|
||||
Debug.LogWarning("connected=[" + connected + "]" + " retCode=[" + (int)retCode + "]" + " msg=[" + msg +"]");
|
||||
if (isClosed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (!connected && isActive)
|
||||
{
|
||||
if (retCode == Errors.serverClosedConnection)
|
||||
{
|
||||
close();
|
||||
}
|
||||
}
|
||||
if (this.onConnectStateChgCallback != null)
|
||||
{
|
||||
ArrayList list = new ArrayList();
|
||||
list.Add(connected);
|
||||
list.Add((int)(retCode));
|
||||
list.Add(msg);
|
||||
this.onConnectStateChgCallback(this, list);
|
||||
}
|
||||
}
|
||||
|
||||
private void connectCallback(IAsyncResult ar)
|
||||
{
|
||||
// 从stateobject获取socket.
|
||||
USocket client = (USocket)ar.AsyncState;
|
||||
if (client.mSocket.Connected)
|
||||
{
|
||||
// 完成连接.
|
||||
client.mSocket.EndConnect(ar);
|
||||
client.isActive = true;
|
||||
client.failTimes = 0;
|
||||
client.onConnectStateChg(true, Errors.success);
|
||||
}
|
||||
else
|
||||
{
|
||||
client.onConnectStateChg(false, Errors.connectFailed);
|
||||
}
|
||||
if (connectTimeout != null)
|
||||
{
|
||||
connectTimeout.Dispose();
|
||||
connectTimeout = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void close()
|
||||
{
|
||||
try
|
||||
{
|
||||
isClosed = true;
|
||||
isActive = false;
|
||||
failTimes = 0;
|
||||
if (mSocket != null)
|
||||
{
|
||||
mSocket.Close();
|
||||
}
|
||||
mSocket = null;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.LogError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void ReceiveAsync(OnReceiveCallback callback)
|
||||
{
|
||||
onReceiveCallback = callback;
|
||||
ReceiveAsync();
|
||||
}
|
||||
|
||||
private void ReceiveAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
// 从远程target接收Number据.
|
||||
mSocket.BeginReceive(mTmpBuffer, 0, mTmpBufferSize, 0,
|
||||
(AsyncCallback)ReceiveCallback, this);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.LogError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void ReceiveCallback(IAsyncResult ar)
|
||||
{
|
||||
USocket client = (USocket)ar.AsyncState;
|
||||
try
|
||||
{
|
||||
if (client.timeoutCheckTimer != null)
|
||||
{
|
||||
client.timeoutCheckTimer.Dispose();
|
||||
client.timeoutCheckTimer = null;
|
||||
}
|
||||
if (client.isActive)
|
||||
{
|
||||
client.failTimes = 0;
|
||||
//从远程设备读取Number据
|
||||
int bytesRead = client.mSocket.EndReceive(ar);
|
||||
if (bytesRead > 0)
|
||||
{
|
||||
//Debug.Log("receive len==" + bytesRead);
|
||||
// 有Number据,存储.
|
||||
onReceiveCallback(client, client.mTmpBuffer, bytesRead);
|
||||
}
|
||||
else if (bytesRead < 0)
|
||||
{
|
||||
client.onConnectStateChg(false, Errors.receivebytesLenError);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 所有Number据读取完毕.
|
||||
Debug.Log("receive zero=====" + bytesRead);
|
||||
client.onConnectStateChg(false, Errors.serverClosedConnection);
|
||||
return;
|
||||
}
|
||||
|
||||
// 继续读取.
|
||||
client.ReceiveAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
client.onConnectStateChg(false, Errors.connectionIsClosed);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Log(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void SendAsync(byte[] data)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (data == null)
|
||||
return;
|
||||
// isOpen始发送Number据到远程设备.
|
||||
if (this.timeoutCheckTimer == null)
|
||||
{
|
||||
this.timeoutCheckTimer = TimerEx.schedule((TimerCallback)sendTimeOut, null, timeoutMSec);
|
||||
}
|
||||
|
||||
mSocket.BeginSend(data, 0, data.Length, 0,
|
||||
(AsyncCallback)SendCallback, this);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.LogError("socket:" + e);
|
||||
onConnectStateChg(false, Errors.sendAsynException);
|
||||
}
|
||||
}
|
||||
|
||||
public void sendTimeOut(object orgs)
|
||||
{
|
||||
failTimes++;
|
||||
if (failTimes > maxTimeoutTimes)
|
||||
{
|
||||
onConnectStateChg(false, Errors.sendTimeout);
|
||||
}
|
||||
}
|
||||
|
||||
private void SendCallback(IAsyncResult ar)
|
||||
{
|
||||
USocket client = (USocket)ar.AsyncState;
|
||||
// 完成Number据发送.
|
||||
int bytesSent = client.mSocket.EndSend(ar);
|
||||
if (bytesSent <= 0) //发送失败
|
||||
{
|
||||
sendTimeOut(null);
|
||||
}
|
||||
else
|
||||
{
|
||||
client.failTimes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
#endif
|
||||
}
|
||||
8
Assets/CoolapeFrame/Scripts/net/USocket.cs.meta
Normal file
8
Assets/CoolapeFrame/Scripts/net/USocket.cs.meta
Normal file
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f8522ac8b7b39488a9f4630092df8850
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
Reference in New Issue
Block a user