Пример #1
0
		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;
                }
			}
		}
Пример #2
0
		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);
			}
		}