用Socket连接,connect到了对方,但是在send时发生异常如下:An existing connection was forcibly closed by the remote host请各位指教,有可能的原因也行,谢谢了

解决方案 »

  1.   

    自己顶!
    我用的是CompactFrameWork3.5
      

  2.   

    An existing connection was forcibly closed by the remote host.
    一个已存在的连接被远程主机强制关闭.我想你要的并不是翻译吧.至于对方为什么强制关闭socket,那原因就多了去了.可能连接超时(短连接且长时间无通讯),可能主机防火墙关的,可能主机连接过多超负荷...
      

  3.   

    谢谢你们的答复!
    服务器程序也是我自己的,一直在执行accept()函数,并没有返回。这期间我尝试用其他程序连这个服务器是可以连接的(Accept函数会返回并继续执行),所以我怀疑是client端的问题。
    代码如下:Client端代码namespace SocketTestClient
    {
        public class SocketClient
        {
            public static void Send(Report report,string ip)
            {
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint ep = new IPEndPoint(Dns.GetHostEntry(ip).AddressList[0], 9999);            socket.Connect(ep);            XmlSerializer xs = new XmlSerializer(typeof(Report));
                StringWriter sw = new StringWriter();            xs.Serialize(sw, report);
                string reportString = sw.GetStringBuilder().ToString();
                byte[] reportBytes = System.Text.Encoding.Default.GetBytes(reportString);            socket.Send(reportBytes);            socket.Shutdown(SocketShutdown.Send);
                socket.Close();
            }
        }
    }Client端的调用        private void UploadInfoItem_Click(object sender, EventArgs e)
            {
                report.userId = "";
                report.longitude = this.LongitudeBox.Text;
                report.latitude = this.LatitudeBox.Text;
                report.satelliteCount = this.SCBox.Text;
                SocketClient.Send(this.report);
            }
      

  4.   

    那么Server和Client都在一台PC上?
    我以前在做并发测试时也有遇上这样的情况,Client在很短时间内开大量socket连接Server...结果大多数socket都遭遇An existing connection was forcibly closed by the remote host...可以参考:http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/81690f44-70be-4f09-b8fb-2017f29b592b
      

  5.   

    谢谢calltaotao,那个连接我看过了,但我这边没有开防火墙,而且只开了一个客户端的时候也不行
      

  6.   

            socket.Send(reportBytes);
    你在他后面怎么就直接?socket.Shutdown(SocketShutdown.Send);他是关闭的意思,你发了一条就关闭了,所以会弹出无法连接,因为你自己给关闭了
      

  7.   

    socket.Send()是阻塞模式地发送,这句走完说明已经发送完成.此时Shutdown然后Close,逻辑上没问题.
    不过Send是静态方法,socket在调用Send时初始化,如果多次调用Send方法则会多次初始化socket.
    如果只UploadInfoItem_Click一次就"An existing connection was forcibly closed by the remote host"我认为可能不是客户端的问题...