コード例 #1
0
        private IEnumerator ConnectSocket(EndPoint endPoint)
        {
            _socket      = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            Status       = SocketStatus.Connecting;
            _asyncResult = _socket.BeginConnect(endPoint, AsyncCallback, _socket);
            float curTime   = 0f;
            float totalTime = 10f;

            while (curTime < totalTime && !_asyncResult.IsCompleted)
            {
                curTime += Time.deltaTime;
                yield return(null);
            }
            bool finish = true;

            try
            {
                _socket.EndConnect(_asyncResult);
                _asyncResult = null;
            }
            catch (Exception e)
            {
                SocketTools.Log("SocketClientType:" + SocketClientType + "连接超时" + "\n" + e.ToString());
                finish = false;
            }
            finally
            {
                _asyncResult = null;
            }
            try
            {
                if (finish)
                {
                    Status    = SocketStatus.Connected;
                    _receiver = new SocketReceiver(this);
                    _sender   = new SocketSender(this);
                }
                else
                {
                    Status = SocketStatus.DisConnected;
                }
            }
            catch (Exception e)
            {
                SocketTools.LogError("SocketClientType:" + SocketClientType + "\n" + e.ToString());
                finish = false;
            }
            finally
            {
                if (_callback != null)
                {
                    Action <bool> temp = _callback;
                    _callback = null;
                    temp.Invoke(finish);
                }
            }
            yield return(null);
        }
コード例 #2
0
 public void RegisterProtoType(ushort ID, Type type)
 {
     lock (lockObj)
     {
         if (_mapProto.ContainsKey(ID))
         {
             SocketTools.Log("has register protoType!ID:" + ID + ",Type:" + type);
         }
         else
         {
             _mapProto.Add(ID, type);
         }
     }
 }
コード例 #3
0
 //这个再主线程调用
 public void Disconnect()
 {
     //可以抛出事件
     SocketTools.Log("socketClient:" + SocketClientType + ",Disconnect");
     this.Close();
 }
コード例 #4
0
 private void AsyncCallback(IAsyncResult ar)
 {
     SocketTools.Log("AsyncCallback");
 }