I'm the gatekeeper of my own destiny

导航

socket 由于目标机器积极拒绝,无法连接的解决办法

        客户最近提出一个需求,要在WEB上远程管理客户端软件。那我们就仿路由器那种模式用SOCKET来解决吧。做了个DEMO,本机测试OK,拿到别的机器上做服务器,提示由于目标机器积极拒绝,无法连接。查询各种资料,有的说是端口没开,有的说是服务没开。各种雾水啊!仔细一想,问题可能出在本机在局域网IP上,而不是用127.0.0.1。更正代码后,问题解决。下面演示服务器端代码的关键部分。

 

 protected void Listen()
        {
            
            MessageBox.Show("start listening");
            string ip = "";
            System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());


            for (int i = 0; i != IpEntry.AddressList.Length; i++)
            {
                if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
                {
                   ip= IpEntry.AddressList[i].ToString();
                }
            }
            IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(ip), 8000);
            Socket sc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sc.Bind(ipend);
           Socket acc;
            while (true)
            { sc.Listen(1);
             acc= sc.Accept();
               
                    byte[] buff = new byte[1024];
                    int recbyte = acc.Receive(buff, buff.Length, 0);
                    if (recbyte == 0)
                        break;
                    string reciveval = "";
                    reciveval += Encoding.GetEncoding("gb2312").GetString(buff, 0, recbyte);
                    string returnval = "开始升级";
                    byte[] returnBy = Encoding.GetEncoding("gb2312").GetBytes(returnval);
                    acc.Send(returnBy, returnBy.Length, 0);
      
            }
            acc.Close();
            sc.Close();
        }

客户端

 

public string sendMessage()
    {
        IPEndPoint ipend = new IPEndPoint(IPAddress.Parse("192.168.XXX.XXX"),8000);
        Socket sc = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        sc.Connect(ipend);
        string message = "请升级软件";
        byte[] bt = Encoding.GetEncoding("gb2312").GetBytes(message);
        sc.Send(bt,bt.Length,0);

        byte[] rebuff = new byte[1024];
        int recive = sc.Receive(rebuff, rebuff.Length, 0);
        string returnval = "";
        returnval += Encoding.GetEncoding("gb2312").GetString(rebuff, 0, recive);
        sc.Close();

        return returnval;
       
    }

 

posted on 2012-03-29 17:02  Wishbay  阅读(5107)  评论(0编辑  收藏  举报