Exemple #1
0
        /// 初始化连接
        public void Connect(string host, int port, Action <Message> callback)
        {
            Assert(netWorkState == NetWorkState.DISCONNECTED);

            UnityEngine.Debug.Log("Connect to " + host + " with port " + port);

            netWorkState = NetWorkState.CONNECTING;

            IPAddress ipAddress = null;

            try
            {
                if (!IPAddress.TryParse(host, out ipAddress))
                {
                    IPAddress[] addresses = Dns.GetHostEntry(host).AddressList;
                    foreach (var item in addresses)
                    {
                        if (item.AddressFamily == AddressFamily.InterNetwork)
                        {
                            ipAddress = item;
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _onDisconnect(e.Message);
                return;
            }

            if (ipAddress == null)
            {
                throw new Exception("Cannot parse host : " + host);
            }

            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ie = new IPEndPoint(ipAddress, port);

            _eventManager.RemoveCallback(SYS_MSG_CONNECTED);
            _eventManager.RemoveCallback(SYS_MSG_CONNECT_FAILED);

            _eventManager.AddCallback(SYS_MSG_CONNECTED, callback);
            _eventManager.AddCallback(SYS_MSG_CONNECT_FAILED, callback);

            _socket.BeginConnect(ie, _onConnectCallback, this._socket);
        }