要在WEB上远程管理客户端软件。那我们就仿路由器那种模式用SOCKET来解决吧。
做了个DEMO,本机测试OK,拿到别的机器上做服务器,提示由于目标机器积极拒绝,无法连接。
查询各种资料,有的说是端口没开,有的说是服务没开。
各种雾水啊!仔细一想,问题可能出在本机在局域网IP上,而不是用127.0.0.1。
更正代码后,问题解决。下面演示服务器端代码的关键部分。
protected void Listen() { MessageBox.Show("start listening"); stringip = ""; System.Net.IPHostEntryIpEntry = 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(); } } IPEndPointipend = 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]; intrecbyte = acc.Receive(buff, buff.Length, 0); if (recbyte == 0) break; stringreciveval = ""; 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() { IPEndPointipend = 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]; intrecive = sc.Receive(rebuff, rebuff.Length, 0); stringreturnval = ""; returnval += Encoding.GetEncoding("gb2312").GetString(rebuff, 0, recive); sc.Close(); returnreturnval; }