简体   繁体   English

c#Socket Closing

[英]c# Socket Closing

I'm working on a http proxy application, everything is working fine (client can connect to server and get contents), the problem is neither of HTTP Server or browser close the TCP connection.. I'm not sure if I'm doing it right, here is the code: 我正在研究一个http代理应用程序,一切正常(客户端可以连接到服务器并获取内容),问题既不是HTTP服务器也不是浏览器关闭TCP连接..我不确定我是否正在做它是对的,这是代码:

while (tcp_link.Connected && _tcp.Connected && !ioError)
{
  try
  {
      Thread.Sleep(100);
      if (streamLink.DataAvailable)
      {
          byte[] l_buffer = new byte[10000];
          int l_read = streamLink.Read(l_buffer, 0, l_buffer.Length);
          byte[] l_data = new byte[l_read];
          Array.Copy(l_buffer, l_data, l_data.Length);

          _stream.Write(l_data, 0, l_data.Length);
      }

      if (_stream.DataAvailable)
      {
          byte[] c_buffer = new byte[10500];
          int c_read = _stream.Read(c_buffer, 0, c_buffer.Length);
          byte[] c_data = new byte[c_read];
          Array.Copy(c_buffer, c_data, c_data.Length);

          streamLink.Write(c_data, 0, c_data.Length);
      }
  }
  catch
  {
      ioError = true;
  }
}

I have same code both sides (proxy client, and proxy server) 我有相同的代码双方(代理客户端和代理服务器)

NOTE: browser will connect to proxy client (which is on the same computer), and proxy client will connect to proxy server, and obviously proxy server will connect to http server, the reason is i wan't to encode data before sending it out 注意:浏览器将连接到代理客户端(在同一台计算机上),代理客户端将连接到代理服务器,显然代理服务器将连接到http服务器,原因是我不想在发送数据之前对数据进行编码

How long have you observed the connection open for? 你有多久观察到连接打开了?

It's very likely that the client uses HTTP 1.1 where Persistent Connections are on by default. 客户端很可能使用默认情况下启用持久连接的HTTP 1.1。

If you're writing a proxy then you should consider: http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html 如果您正在编写代理,那么您应该考虑: http//www.w3.org/Protocols/rfc2616/rfc2616-sec8.html

Okay i found the problem, who ever is out there having problem with closing socket connection.. 好吧,我发现了问题,谁在外面有关闭套接字连接的问题..

Actually, Socket.Available isn't working as i expected, to see if a socket is really connected you should check both Available and Poll properties, below function should resolve your problem: thanks to: zendar 实际上, Socket.Available没有按照我的预期工作,看看套接字是否真正连接你应该检查Available和Poll属性,下面的函数应该可以解决你的问题: 感谢:zendar

bool SocketConnected(Socket s)
{
      bool part1 = s.Poll(1000, SelectMode.SelectRead);
      bool part2 = (s.Available == 0);
      if (part1 & part2)
            return false;
      else
            return true;
}

i hope this solve your problem too ;) 我希望这也能解决你的问题;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM