473,804 Members | 3,228 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Socket locking up after inital use

Hi,

I am trying to get a webpage using a TcpSocket instead of a standard
Webrequest. Initial, it works fine but after the 2 or 3 request the
tcpclient I start to get the following error:

A connection attempt failed because the connected party did not properly
respond after a period of time, or established connection failed because
connected host has failed to respond

Here is the code making the call, this is the third iteration after trying
several others with out sucess:

string contents = "GET " + pathQuery + " HTTP/1.1\r\n" +
"Host: " + host + ":" + port + "\r\n" +
"User-Agent: Mozilla/5.0 (Windows; U; Windows
NT 6.0; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4\r\n" +
"Accept:
text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,ima ge/png,*/*;q=0.5\r\n" +
"Accept-Language: en-us,en;q=0.5\r\n " +
"Accept-Encoding: gzip,deflate\r\ n" +
"Accept-Charset:
ISO-8859-1,utf-8;q=0.7,*;q=0.7 \r\n" +
"Keep-Alive: 300\r\n" +
"Connection : keep-alive\r\n\r\n";

Byte[] requestObject = Encoding.ASCII. GetBytes(conten ts.ToCharArray( ));
try
{
stream = socket.GetStrea m();

if (stream.CanWrit e)
{
stream.Write(re questObject, 0, contents.Length );
}

MemoryStream memoryStream = new MemoryStream();

if (stream.CanRead )
{
int data = stream.ReadByte ();
while (data != -1)
{
memoryStream.Wr iteByte((byte) data);
data = stream.ReadByte ();
}
results =
Encoding.ASCII. GetString(memor yStream.ToArray ());
}

}
catch (Exception e)
{

Console.WriteLi ne(Encoding.ASC II.GetString(me moryStream.ToAr ray()));
throw e;
}
finally
{
stream.Close();
socket.Close();
}

Jun 29 '07 #1
3 3090
On Fri, 29 Jun 2007 13:22:05 -0700, Pain and headache <Pain and
<he******@discu ssions.microsof t.com>wrote:
I am trying to get a webpage using a TcpSocket instead of a standard
Webrequest. Initial, it works fine but after the 2 or 3 request the
tcpclient I start to get the following error:

A connection attempt failed because the connected party did not properly
respond after a period of time, or established connection failed because
connected host has failed to respond [...]
Some thoughts:

* You say you get an error trying to make the connection. But you
didn't bother to post any code related to creating or connecting your TCP
socket.

* As far as I know, there's no such thing as a TcpSocket, nor is there
a Socket.GetStrea m() method. You can create a Socket instance that
encapsulates a TCP socket, and you can create a NetworkStream instance
using a Socket instance. Is that what you did? If so, why does your post
and code say something else? And if not, what _did_ you do?

All that said, assuming your code normally works, you may be running into
some kind of anti-DoS defense, depending on how you're using the code. If
you are repeatedly trying to make the same request to the same HTTP
server, it may detect that case and stop responding, at least for some
time.

If you can post a concise-but-complete example of code, client _and_
server, that reliably reproduces the problem, someone here may be able to
provide better advice. Absent that, there's not much in your post to go
on, and in fact what you posted doesn't make much sense in the context of
regular .NET/C# programming (since you mention a class and a method that
are simply not present in the basic .NET Framework).

Pete
Jun 29 '07 #2
I am very sorry for the confusing. I was trying to be brief. Here is the
class, and I renamed the socket to client for easyier reading. I am using
TCPTrace at the moment to test this, and it gets and sends the proper
responses so I do not believe it is a Dos prevention of some kind.

using System;
using System.IO;
using System.Net.Sock ets;
using System.Text;

namespace ReanneCorp.Libr ary.V2.Common.W ebUtils
{
public class PullWebsiteClas s
{
private Uri websiteUri;
private TcpClient client = null;
private string results = "";
private int port;
private string host;
private string pathQuery;

public Uri WebsiteUri
{
get { return websiteUri; }
set { websiteUri = value; }
}

public TcpClient Client
{
get { return client; }
set { client = value; }
}

public NetworkStream Stream
{
get { return stream; }
set { stream = value; }
}

public string Results
{
get { return results; }
set { results = value; }
}
public PullWebsiteClas s(Uri websiteUri)
{
this.websiteUri = websiteUri;
InitConnection( );
}
private void InitConnection( )
{
port = websiteUri.Port ;
host = websiteUri.Host ;
pathQuery = websiteUri.Path AndQuery;

client = new TcpClient();
client.ReceiveT imeout = 10000;
try
{
client.Connect( host, port);
}
catch(SocketExc eption ex)
{
throw ex;
}
}
public void MakePageRequest ()
{
string contents = "GET " + pathQuery + " HTTP/1.1\r\n" +
"Host: " + host + ":" + port + "\r\n" +
"User-Agent: Mozilla/5.0 (Windows; U; Windows
NT 6.0; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4\r\n" +
"Accept:
text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,ima ge/png,*/*;q=0.5\r\n" +
"Accept-Language: en-us,en;q=0.5\r\n " +
"Accept-Encoding: gzip,deflate\r\ n" +
"Accept-Charset:
ISO-8859-1,utf-8;q=0.7,*;q=0.7 \r\n" +
"Keep-Alive: 300\r\n" +
"Connection : keep-alive\r\n\r\n";
MemoryStream memoryStream = new MemoryStream();

Byte[] requestObject =
Encoding.ASCII. GetBytes(conten ts.ToCharArray( ));
try
{
stream = client.GetStrea m();

if (stream.CanWrit e)
{
stream.Write(re questObject, 0, contents.Length );
}
if (stream.CanRead )
{
int data = stream.ReadByte ();
while (data != -1)
{
memoryStream.Wr iteByte((byte) data);
data = stream.ReadByte ();
}
results =
Encoding.ASCII. GetString(memor yStream.ToArray ());
}

if (results.Contai ns("HTTP/1.1 302 Moved Temporarily"))
{
client.Close();
string redirect = results.Remove( 0,
results.IndexOf ("Location: ") + 10);
redirect = redirect.Substr ing(0,

redirect.IndexO f("Content-Length:") - 1).Trim();

PullWebsiteClas s newRequest = new PullWebsiteClas s(new
Uri(redirect));
newRequest.Make PageRequest();
results = newRequest.Resu lts;
}
}
catch (Exception e)
{
throw e
}
finally
{
memoryStream.Cl ose();
client.Close();
}
}
}
}
Here is the calling code:

[Test]
public void CheckHeaders()
{

PullWebsiteClas s getPage = new PullWebsiteClas s(new
Uri("http://localhost:8081/test.aspx"));
getPage.MakePag eRequest();
string page = getPage.Results ;
Console.WriteLi ne(page);
Assert.AreNotEq ual(page.Length , 0);
}


"Peter Duniho" wrote:
On Fri, 29 Jun 2007 13:22:05 -0700, Pain and headache <Pain and
<he******@discu ssions.microsof t.com>wrote:
I am trying to get a webpage using a TcpSocket instead of a standard
Webrequest. Initial, it works fine but after the 2 or 3 request the
tcpclient I start to get the following error:

A connection attempt failed because the connected party did not properly
respond after a period of time, or established connection failed because
connected host has failed to respond [...]

Some thoughts:

* You say you get an error trying to make the connection. But you
didn't bother to post any code related to creating or connecting your TCP
socket.

* As far as I know, there's no such thing as a TcpSocket, nor is there
a Socket.GetStrea m() method. You can create a Socket instance that
encapsulates a TCP socket, and you can create a NetworkStream instance
using a Socket instance. Is that what you did? If so, why does your post
and code say something else? And if not, what _did_ you do?

All that said, assuming your code normally works, you may be running into
some kind of anti-DoS defense, depending on how you're using the code. If
you are repeatedly trying to make the same request to the same HTTP
server, it may detect that case and stop responding, at least for some
time.

If you can post a concise-but-complete example of code, client _and_
server, that reliably reproduces the problem, someone here may be able to
provide better advice. Absent that, there's not much in your post to go
on, and in fact what you posted doesn't make much sense in the context of
regular .NET/C# programming (since you mention a class and a method that
are simply not present in the basic .NET Framework).

Pete
Jun 29 '07 #3
On Fri, 29 Jun 2007 14:02:03 -0700, Pain and headache
<Pa************ *@discussions.m icrosoft.comwro te:
I am very sorry for the confusing. I was trying to be brief. Here is
the
class, and I renamed the socket to client for easyier reading. I am
using
TCPTrace at the moment to test this, and it gets and sends the proper
responses so I do not believe it is a Dos prevention of some kind.
Well, I don't see anything obvious. As I mentioned, you really need to
post a _complete_ sample of code that reliably reproduces the problem if
anyone is to actually try to look at your specific problem. You've only
posted the client side of things.

There do happen to be some odd things in your code, even without me
inspecting each line carefully (which I didn't do). Nothing that seems
like it would be causing the issue, but which are to me a sign of
less-than-perfect code:

-- When you write to the NetworkStream, you use the length of the
original string, not the byte array you're passing. In this case, they
should be the same, but there are potential situations in which they
wouldn't be. You should pass the length of the actual data you expect to
send, not some other length that is related but not necessarily identical.

-- You check the CanWrite and CanRead properties of the stream, but
don't do anything sensible if they aren't what you expect. One particular
issue is that if CanWrite is false but CanRead is true, you skip trying to
write but go ahead and try to read a response to something you never
sent. That makes no sense. Presumably, both CanWrite and CanRead are
true in this situation, so the oddity shouldn't affect you. But the code
is wrong, nevertheless.

-- You are catching exceptions that you then do nothing with other
than to throw them again. What's the point?

Have you tried not setting the timeout? It's not supposed to affect
connecting, but maybe it does, or maybe having a timeout on a previous
connection somehow interferes with the subsequent one. I admit, I'm just
making wild guesses here...I don't see anything obvious. Even more reason
for you to construct self-contained server/client sample code that
reliably reproduces the problem. Just looking at the code doesn't suggest
anything obvious, at least not to me.

Pete
Jun 29 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3372
by: Jane Austine | last post by:
Running Python 2.3 on Win XP It seems like socket is working interdependently with subprocesses of the process which created socket. ------------------------------------ #the server side >>> import socket >>> s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) >>> s.bind(('localhost',9000))
1
6139
by: Joe | last post by:
Hi, I browsed the news and a few seem to have this problem too, but no solution ! I have a client server application where in case the connection gets bad (crashes or whatever) client or server (who knows it first) closes the socket and than wants to establish the SAME connection again ( due to firewall reasons it has to be the SAME IP AND PORT).
4
7092
by: zbcong | last post by:
Hello: I write a multithread c# socket server,it is a winform application,there is a richtextbox control and button,when the button is click,the server begin to listen the socket port,waiting for a incoming connection,the relative code snipprt as following:: private IPAddress myIP=IPAddress.Parse("127.0.0.1"); private IPEndPoint myServer; private Socket socket; private Socket accSocket; private System.Windows.Forms.Button button2;...
5
3689
by: John Sheppard | last post by:
Hi all, I am not sure that I am posting this in the right group but here it goes anyway. I am new to socket programming and I have been searching on the internet to the questions I am about to pose but have been unsuccessful in finding the answers so far. Either because my understanding of sockets isn't where it needs to be or my questions are too basic. My programming environment is Windows XP, Visual Studio .NET 2003 and C#. So here it...
4
18139
by: Chris Tanger | last post by:
Context: C# System.Net.Sockets Socket created with constructor prarmeters Internetwork, Stream and TCP everything else is left at the default parameters and options except linger may be changed as I find appropriate. I am using the socket asynchronously by calling the BeingSend and BeginReceive calls. I would like to be able to call shutdown and close asynchronously if possible.
15
6204
by: z. f. | last post by:
Hi, i have an ASP.NET project that is using a (Class Library Project) VB.NET DLL. for some reason after running some pages on the web server, and trying to compile the Class Library DLL, it can't compile because the DLL is in use (and the PDB too), and the w3wp.exe process is the process locking the DLL (as viewed with Sysinternals - Process Explorer). this is a huge problem. i need to do IIS reset in order to free the DLL! 1. why is...
6
4253
by: Rik | last post by:
Hello Experts, I have a communication server in VB.NET. It was working fine from last 6 months, but now start giving error message like that. 21-03-2005 07:58:27 DoListenSystem.Net.Sockets.SocketException: A blocking operation was interrupted by a call to WSACancelBlockingCall at System.Net.Sockets.Socket.Accept() at System.Net.Sockets.TcpListener.AcceptTcpClient() at ProjectCommServer.CommServer.DoListen()
4
2769
by: Macca | last post by:
I am writing an application that uses asynchronous sockets to get data over ethernet from embedded devices, up to 30 concurrent devices.(These devices are written in C). My application implements an asychronous socket server while the embedded devices are the clients When the data comes in over the socket it is eventually passed into a message queue.
2
18382
by: kodart | last post by:
Introduction Performance is the main concern to most server application developers. That’s why many of them anticipate using .NET platform to develop high performance server application regardless of the security features it provides. Microsoft Windows provides a high performance model that uses I/O completion port (IOCP) to process network events. IOCP provides best performance, but difficult to use due to lack of good code samples and...
0
9588
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10589
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10340
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10085
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9161
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7625
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3828
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.