private void connectCallback (IAsyncResult ar) { // 从stateobject获取socket. USocket client = (USocket)ar.AsyncState; try { if (client.mSocket.Connected) { // 完成连接. client.mSocket.EndConnect (ar); client.IsConnectionSuccessful = true; client.isActive = true; // isOpen始接Number据 // client.ReceiveAsync (); client.connectCallbackFunc (client, true); client.failTimes = 0; } else { client.connectCallbackFunc (client, false); client.close (); } } catch (Exception e) { client.IsConnectionSuccessful = false; Debug.Log ("connect faile:" + e); client.failTimes++; client.connectCallbackFunc (client, false); client.close (); } finally { if(connectTimeout != null) { connectTimeout.Dispose(); connectTimeout = null; } } }
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据,存储. client.mBuffer.Write (client.mTmpBuffer, 0, bytesRead); OnReceiveCallback (client, client.mBuffer); } else if (bytesRead < 0) { if (client.offLineCallback != null) { client.offLineCallback (client, null); } client.connectCallbackFunc (client, false); client.close (); } else { // 所有Number据读取完毕. Debug.Log ("receive zero=====" + bytesRead); if (client.offLineCallback != null) { client.offLineCallback (client, null); } client.connectCallbackFunc (client, false); client.close (); return; } // 继续读取. if (client.mSocket.Connected) { client.mSocket.BeginReceive (client.mTmpBuffer, 0, client.mTmpBufferSize, 0, (AsyncCallback)ReceiveCallback, client); } } else { if (client.offLineCallback != null) { client.offLineCallback (client, null); } client.connectCallbackFunc (client, false); client.close (); } } catch (Exception e) { if (client.offLineCallback != null) { client.offLineCallback (client, null); } client.connectCallbackFunc (client, false); client.close (); Debug.Log (e); } }
private object defaultUnpackMsg(USocket s, MemoryStream buffer) { object ret = null; long oldPos = buffer.Position; long tatalLen = buffer.Length; long needLen = B2InputStream.readInt(buffer); if (needLen <= 0 || needLen > __maxLen) { // 网络Number据错误。断isOpen网络 outofLine(s, false); s.close(); return(null); } long usedLen = buffer.Position; if (usedLen + needLen <= tatalLen) { ret = B2InputStream.readObject(buffer); } else { //说明长度不够 buffer.Position = oldPos; } return(ret); }
public void stop() { isStopping = true; connected = false; if (socket != null) { socket.close(); } socket = null; }
private void SendCallback (IAsyncResult ar) { USocket client = (USocket)ar.AsyncState; // 完成Number据发送. int bytesSent = client.mSocket.EndSend (ar); if (bytesSent <= 0) { //发送失败 if (client.offLineCallback != null) { client.offLineCallback (client, null); } client.close (); } client.failTimes = 0; }