Esempio n. 1
0
    // 连接服务器
    public void ConnectServer(string ip, int port, Action <Connection, string> callback)
    {
        NC.Close();

        Debug.Log("ConnectServer " + ip + ":" + port);

#if UNITY_IPHONE && !UNITY_EDITOR
        String newServerIp = "";

        AddressFamily newAddressFamily = AddressFamily.InterNetwork;
        IPv6SupportMidleware.getIPType(ip, port.ToString(), out newServerIp, out newAddressFamily);

        UnityEngine.Debug.Log("ConnectServer use IPv6 ? " + (newAddressFamily == AddressFamily.InterNetworkV6 ? "Yes" : "No"));

        NC.Connect2Peer(newServerIp, port, newAddressFamily, (Connection conn, string reason) => {
            ResetAllConnection(conn);
            callback(conn, reason);
        });
#else
        NC.Connect2Peer(ip, port, (Connection conn, string reason) =>
        {
            ResetAllConnection(conn);
            callback(conn, reason);
        });
#endif
    }
Esempio n. 2
0
        public bool Connect(string hostName, int serviceport)
        {
            if (mIsConnected)
            {
                ExceptionCode    = SOCKET_ERRCODE.ERR_CONNECT;
                ExceptionMessage = "error; socket has already connected!";
                return(false);
            }
            String        newServerIp      = "";
            AddressFamily newAddressFamily = AddressFamily.InterNetwork;

            IPv6SupportMidleware.getIPType(hostName, serviceport.ToString(), out newServerIp, out newAddressFamily);
            mSocket                = new Socket(newAddressFamily, SocketType.Stream, ProtocolType.Tcp);
            mSocket.SendTimeout    = 40 * 1000;     //40s
            mSocket.ReceiveTimeout = 40 * 1000;     //40s

            mSendList.Clear();
            mSendTime = 0;

            try
            {
                mSocket.BeginConnect(newServerIp, serviceport, new AsyncCallback(mSocketManager.AyncConnectCallback), this);
            }
            catch (Exception ex)
            {
                ExceptionCode    = SOCKET_ERRCODE.ERR_CONNECT;
                ExceptionMessage = ex.Message;
                return(false);
            }

            return(true);
        }
Esempio n. 3
0
        //连接
        public void Connect()
        {
            if (isConnected || m_connectState == ConnectState.Connnecting)
            {
                Debug.Log("已经连接上了,别再连接,会出事的!");
                return;
            }
            string        strNewIp         = "";
            AddressFamily newAddressFamily = AddressFamily.InterNetwork;

            IPv6SupportMidleware.getIPType(mIp, mPort.ToString(), out strNewIp, out newAddressFamily);
            Debug.Log(" Socket AddressFamily :" + newAddressFamily.ToString() + "原始ip:" + mIp + ", 结果ip:" + strNewIp + ",端口:" + mPort);

            m_client                   = new TcpClient(newAddressFamily);
            m_client.SendTimeout       = 1000;
            m_client.ReceiveTimeout    = 5000;
            m_client.NoDelay           = true;
            m_client.SendBufferSize    = 1024 * 8;
            m_client.ReceiveBufferSize = NetConst.TMP_BUF_SIZE;
            m_client.Client.Blocking   = true;
            m_connectState             = ConnectState.Connnecting;
            try
            {
                m_client.BeginConnect(strNewIp, mPort, new AsyncCallback(OnConnect), m_client);
            }
            catch (Exception e)
            {
                //*设置失败次数++
                Debug.Log("连接不通:" + e.Message + " ==>" + e.ToString());
                m_connectState = ConnectState.ConnectFail;
                OnDisconnected(DisType.ConnectTimeOut, "连接游戏服务器失败!(-1)");
            }
        }
Esempio n. 4
0
    /// <summary>
    /// 连接服务器
    /// </summary>
    void ConnectServer(string host, int port)
    {
        //if( RecUtil.GetInstance().IsRec() )
        //{
        String        newServerIp      = "";
        AddressFamily newAddressFamily = AddressFamily.InterNetwork;

        IPv6SupportMidleware.getIPType(host, port.ToString(), out newServerIp, out newAddressFamily);
        if (!string.IsNullOrEmpty(newServerIp))
        {
            host = newServerIp;
        }
        client                = null;
        client                = new TcpClient(newAddressFamily);
        client.SendTimeout    = 60000;
        client.ReceiveTimeout = 60000;
        client.NoDelay        = true;

        try
        {
            client.BeginConnect(host, port, new AsyncCallback(OnConnect), null);
        }
        catch (Exception e)
        {
            OnDisconnected(Protocal.ConnectFail, -1000, e.Message);
        }
        //}
    }
Esempio n. 5
0
        protected override void DoConnect()
        {
            AddressFamily newAddressFamily = AddressFamily.InterNetwork;

            IPv6SupportMidleware.getIPType(mIp, mPort.ToString(), out newAddressFamily);

            mClientSocket = new Socket(newAddressFamily, SocketType.Stream, ProtocolType.Tcp);
            mClientSocket.BeginConnect(mIp, mPort, (IAsyncResult ia) =>
            {
                mClientSocket.EndConnect(ia);
                OnConnected();
            }, null);
            mStatus = SOCKSTAT.CONNECTING;
        }
Esempio n. 6
0
    //public void CheckNetState()
    //{
    //    if (socket == null)
    //    {
    //        return;
    //    }
    //    //DateTime start = DateTime.Now;
    //    UnityEngine.NetworkReachability state = UnityEngine.Application.internetReachability;
    //    if (state == UnityEngine.NetworkReachability.NotReachable)
    //    {
    //        IsNetStateChange = true;
    //        UnityEngine.Debug.Log("IsNetStateChange = true" + state.ToString());
    //    }
    //    else if (NetState != state)//处理3G 2G的情况
    //    {
    //        UnityEngine.Debug.Log("IsNetStateChange = true" + state.ToString());
    //        IsNetStateChange = true;
    //    }
    //    //UnityEngine.Debug.Log("CheckTime" + DateTime.Now.Subtract(start).TotalMilliseconds );
    //}

    /// <summary>
    /// 打开连接
    /// </summary>
    public void Open()
    {
        isConnect = false;
        UnityEngine.NetworkReachability state = UnityEngine.Application.internetReachability;
        if (state != UnityEngine.NetworkReachability.NotReachable)
        {
            String        newServerIp      = "";
            AddressFamily newAddressFamily = AddressFamily.InterNetwork;
            IPv6SupportMidleware.getIPType(_host, _port.ToString(), out newServerIp, out newAddressFamily);
            if (string.IsNullOrEmpty(newServerIp))
            {
                newServerIp = _host;
            }
            //Debug.LogError("444444444444444444OpenOpenOpenOpenOpenOpenOpenOpen");
            _socket = new Socket(newAddressFamily, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                _socket.BeginConnect(newServerIp, _port, asyncResult =>
                {
                    try
                    {
                        _socket.EndConnect(asyncResult);
                        if (_heartbeatThread == null)
                        {
                            _heartbeatThread = new Timer(SendHeartbeatPackage, null, HearInterval, HearInterval);
                        }

                        _thread = new Thread(new ThreadStart(CheckReceive));
                        _thread.Start();
                        isConnect = true;
                        Net.Instance.QueueEvent(EventDef.ServerConnectFinish);
                    }
                    catch (SocketException ex)
                    {
                        isConnect = false;
                        Net.Instance.QueueEvent(EventDef.ServerConnectFailure, ex.ToString());
                    }
                    //_socket.Connect(newServerIp, _port);
                }, null);
            }
            catch
            {
                //socket.Dispose();
                _socket = null;
                throw;
            }
        }
    }
Esempio n. 7
0
        protected override void DoConnect()
        {
            String        newServerIp      = "";
            AddressFamily newAddressFamily = AddressFamily.InterNetwork;

            IPv6SupportMidleware.getIPType(mIp, mPort.ToString(), out newServerIp, out newAddressFamily);
            if (!string.IsNullOrEmpty(newServerIp))
            {
                mIp = newServerIp;
            }

            mClientSocket = new Socket(newAddressFamily, SocketType.Stream, ProtocolType.Tcp);
            mClientSocket.BeginConnect(mIp, mPort, (IAsyncResult ia) =>
            {
                mClientSocket.EndConnect(ia);
                OnConnected();
            }, null);
        }
Esempio n. 8
0
        private void ConnThread()
        {
            IPAddress ip = null;

            IPAddress[] ipAry = Dns.GetHostAddresses(_host);
            foreach (IPAddress ipAddress in ipAry)
            {
                if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
                {
                    ip = ipAddress;
                    break;
                }
            }
            IPEndPoint ipEndPoint = new IPEndPoint(ip, _port);

#if UNITY_EDITOR
            _socket          = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.Blocking = true;
            _socket.Connect(ipEndPoint);
#endif

#if UNITY_ANDROID
            //IPEndPoint ipEndPoint = new IPEndPoint(ip, _port);
            _socket          = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.Blocking = true;
            _socket.Connect(ipEndPoint);
#endif
#if UNITY_IOS
            AddressFamily addressFamily = AddressFamily.InterNetwork;
            string        newIPAddress  = string.Empty;
            IPv6SupportMidleware.getIPType(ip.ToString(), _port.ToString(), out newIPAddress, out addressFamily);

            _socket          = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
            _socket.Blocking = true;
            _socket.Connect(newIPAddress, _port);
#endif
            _recvStream = new MemoryStream();
            _recvThread = new Thread(new ThreadStart(RecvThread));
            _sendThread = new Thread(new ThreadStart(SendThread));
            _recvThread.Start();
            _sendThread.Start();
            _connThread = null;
        }
Esempio n. 9
0
        private void HandleConnect(tReqHead pReq)
        {
            if (pReq == null)
            {
                return;
            }
            tReqConnect pConnect = (tReqConnect)pReq;
            string      ipv4     = pConnect.szRemoteIp;
            int         port     = pConnect.uRemotePort;

            //---------------use ipv6 to connect to gameserver-------------
            String        newServerIp      = "";
            AddressFamily newAddressFamily = AddressFamily.InterNetwork;

            IPv6SupportMidleware.getIPType(ipv4, port.ToString(), out newServerIp, out newAddressFamily);
            if (!string.IsNullOrEmpty(newServerIp))
            {
                ipv4 = newServerIp;
            }
            //-------------------------------------------------------------
            mSocket = new Socket(newAddressFamily, SocketType.Stream, ProtocolType.Tcp);
            if (mSocket == null)
            {
                // not used
                SetClientState(eClientState.eClient_STATE_CONNECT_FAIL);
                return;
            }

            //	mSocketList[0] = mSocket;

            mSocket.SendTimeout    = 0;
            mSocket.ReceiveTimeout = 0;
            //mSocket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 0);
            //mSocket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);

            bool non = pConnect.timeOut >= 0;

            /*
             * if (non)
             *  mSocket.Blocking = false;
             * else
             *  mSocket.Blocking = true;
             */
            if (non)
            {
                // set waiting = true
                mWaiting.Reset();

                AsyncCallback callBack = new AsyncCallback(OnConnectCallBack);
                mSocket.BeginConnect(ipv4, port, callBack, mSocket);

                //阻塞当前线程,直到当前的 WaitHandle 收到信号
                //返回值:如果当前实例收到信号,则为 true;否则为 false。
                if (mWaiting.WaitOne(pConnect.timeOut))
                {
                    if (mSocket.Connected && mSocket.Poll(0, SelectMode.SelectWrite))
                    {
                        SetClientState(eClientState.eClient_STATE_CONNECTED);
                    }
                    else
                    {
                        CloseSocket();
                        SetClientState(eClientState.eClient_STATE_CONNECT_FAIL);
                    }
                }
                else
                {
                    if (mSocket.Connected && mSocket.Poll(0, SelectMode.SelectWrite))
                    {
                        SetClientState(eClientState.eClient_STATE_CONNECTED);
                    }
                    else
                    {
                        CloseSocket();
                        SetClientState(eClientState.eClient_STATE_CONNECT_FAIL);
                    }
                }
            }
            else
            {
                //阻塞式
                // yi zhi waiting...
                try
                {
                    mSocket.Connect(ipv4, port);
                    if (mSocket.Connected && mSocket.Poll(0, SelectMode.SelectWrite))
                    {
                        SetClientState(eClientState.eClient_STATE_CONNECTED);
                    }
                    else
                    {
                        CloseSocket();
                        SetClientState(eClientState.eClient_STATE_CONNECT_FAIL);
                    }
                }
                catch (Exception e)
                {
                    CloseSocket();
                    SetClientState(eClientState.eClient_STATE_CONNECT_FAIL);
                }
            }
        }
Esempio n. 10
0
    // 执行登录操作
    public void OnLogin()
    {
        var srvAddr     = SrvAddr.text;
        var srvPort     = 9530;
        var addrFamily  = AddressFamily.InterNetwork;
        var acc         = SystemInfo.deviceUniqueIdentifier;
        var version     = Application.version;
        var deviceModel = SystemInfo.deviceModel.ToString();
        var buildNo     = "002";

        GetPlatform();

    #if UNITY_IPHONE && !UNITY_EDITOR
        IPv6SupportMidleware.getIPType(srvAddr, srvPort.ToString(), out srvAddr, out addrFamily);
    #endif

        // 连接服务器
        var gc = GameCore.Instance;
        var nc = gc.Get <NetCore>();
        SetTips("连接服务器 ...");
        nc.Connect2Peer(srvAddr, srvPort, (conn, reason) =>
        {
            if (conn == null)
            {
                SetTips(reason);
            }
            else
            {
                gc.ServerConnection = conn;

                // 登录
                SetTips("请求登录 ...");
                var buff = conn.Request2Srv("Login", (data) =>
                {
                    var isNewVersion = data.ReadBool();
                    if (!isNewVersion)
                    {
                        downloadURL = data.ReadString();

                        SetTips("请更新到最新版本!");
                        DownloadBtn.SetActive(true);
                        LoginBtn.SetActive(false);
                        return;
                    }
                    else
                    {
                        DownloadBtn.SetActive(false);
                        LoginBtn.SetActive(true);
                    }

                    var ok = data.ReadBool();
                    if (ok)
                    {
                        PlayerPrefs.SetString("ServerAddress", srvAddr);

                        SetTips("登录成功");
                        GameCore.Instance.MeID   = acc;
                        GameCore.Instance.MeInfo = data.Read <UserInfo>();
                        Hide();
                        UIManager.Instance.ShowTopUI("MainMenu", true);
                        UIManager.Instance.ShowTopUI("MainArea", true);

                        UnitConfigUtil.GetUnitCfgsFromServer();
                        UserManager.SyncAvatarsFromCfg();

                        var qName = data.ReadString();

                        if (!string.IsNullOrEmpty(qName))
                        {
                            QAUI.OnGetQuestionnaire(qName);
                        }
//                        StaticSoundMgr.Instance.PlaySound("Login");
                    }
                    else
                    {
                        SetTips("登录失败");
                        conn.Close();
                    }
                }, (conntected) =>
                {
                    SetTips("登录超时");
                    if (conntected)
                    {
                        conn.Close();
                    }
                });

                buff.Write(acc);
                buff.Write(version);
                buff.Write(platform);
                buff.Write(deviceModel);
                buff.Write(buildNo);
                conn.End(buff);
            }
        }, addrFamily);
    }