2 tongtong9680 tongtong9680 于 2014.05.06 16:51 提问

设备连接服务器,从代码上看是同时产生连个socket进行通信吗?有何影响?

设备连接服务器端有两个端口,是同时建立socket通信吗?两个socket连接同时产生吗?如果其中一个端口发生阻塞,设备与服务器连接就全部发生再另外一个socket连接上吗?

代码如下:

CheckServerConnect(Global.Hitems1stIP, Global.Hitems1stPort, lblHiTems1stStatus);
CheckServerConnect(Global.Hitems2ndIP, Global.Hitems2ndPort, lblHiTems2ndStatus);

#endregion

    #region CheckServerConnect

    private void CheckServerConnect(string ip, int port, Label lbl)
    {
        Thread thread = new Thread(new ThreadStart(delegate() { DoCheck(ip, port, lbl); }));
        thread.Start();
    }

    private void DoCheck(string ip, int port, Label lbl)
    {
        IPEndPoint ipep = null;
        Socket socket = null;

        try
        {
            ipep = new IPEndPoint(IPAddress.Parse(ip), port);
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(ipep);

            SetLabel(lbl, Color.Blue, "Connected");
        }
        catch //(Exception e)
        {
            SetLabel(lbl, Color.Red, "Disconnected");
        }
        finally
        {
            if (ipep != null) { ipep = null; }
            if (socket != null) { socket.Close(); socket = null; }
        }
    }

    delegate void SetLabelInvoker(Label lbl, Color backColor, string message);
    private void SetLabel(Label lbl, Color backColor, string message)
    {
        try
        {
            if (lbl.InvokeRequired)
            {
                lbl.BeginInvoke(new SetLabelInvoker(SetLabel), lbl, backColor, message);
                return;
            }
            lbl.BackColor = backColor;
            lbl.Text = message;
        }
        catch { }
    }

    #endregion
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!