473,789 Members | 2,898 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Threaded TCP socket program incorrectly reporting establishment of connection

Hi Group,

A question about threads and asynchronous TCP sockets. In the
attached code, even if the host TCP server is not running my code
reports that the connection has been established.

With the Server NOT listening I get (Even actually the system powered
off)

connectHost Started
connectHost Complete
connectHostCall back Started
connectHostCall back Socket Connected

Why is the attached code reporting that the connection is establish
ed?

If I call a sligtly modified version of the same code in a single
class the connection status is reported correctly.

Thanks

Mark

using System;
using System.Collecti ons.Generic;
using System.Text;
using System.Threadin g;
using System.Net;
using System.Net.Sock ets;
using System.IO;

namespace ASYNC
{
class Program
{
static void Main(string[] args)
{
ConnectionClass client = new ConnectionClass ();
Thread firstThread = new Thread(new
ThreadStart(cli ent.connectHost ));
firstThread.Nam e = "Client";
firstThread.Sta rt();
Thread.Sleep(10 000);
}
}

public class ConnectionClass
{
private static Socket socketHost;

public ConnectionClass ()
{
socketHost = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p);
}

private void connectHostCall back(IAsyncResu lt asyncResult)
{
Console.WriteLi ne("connectHost Callback Started");
Socket sock = (Socket)asyncRe sult.AsyncState ;

try
{
sock.EndConnect (asyncResult);
Console.WriteLi ne("connectHost Callback Socket
Connected");
}
catch
{
Console.WriteLi ne("connectHost Callback Socket Failed
to Connect");
}
}

public void connectHost()
{
Console.WriteLi ne("connectHos t Started");
IPEndPoint remoteServerEnd Point = new
IPEndPoint(IPAd dress.Parse("19 2.168.1.10"), 8888);
AsyncCallback asyncConnectHos t = new
AsyncCallback(c onnectHostCallb ack);
IAsyncResult statusConnect =
socketHost.Begi nConnect(remote ServerEndPoint, asyncConnectHos t,
socketHost);
Console.WriteLi ne("connectHos t Complete");
}

public class StateObject
{
public Socket stateSocket = null;
public const int BufferSize = 1500;
public byte[] buffer = new byte[BufferSize];
}
}
}

Mar 31 '07 #1
4 1797
On Sat, 31 Mar 2007 03:44:03 -0700, <sh******@yahoo .com.auwrote:
[...]
Why is the attached code reporting that the connection is establish
ed?

If I call a sligtly modified version of the same code in a single
class the connection status is reported correctly.
You say that a "slightly modified version of the same code" works fine.
Why did you not provide details as to what you changed in the code to make
it work? It seems to me that would be useful information.

That said, it appears to me that the issue you're having is that the
thread where you issue the async connection request exits before the
request has completed. When that happens, the operation completes
immediately and without error. I suspect that it wasn't moving the code
into a single class that caused your problem to go away, but rather not
creating the extra thread.

I don't understand why the AsyncResult appears to be tied to a thread, and
I don't understand why EndConnect doesn't throw an exception, given that
the socket isn't connected when you call it. But I suspect that's a .NET
thing that other, more experience .NET folks can comment on.

For your immediate needs, I would recommend not creating a new thread just
for the purpose of starting the connection request. It doesn't seem to
serve any purpose (the code in the thread executes nearly instantly) and
is the fundamental cause of the issue you're seeing.

Pete
Mar 31 '07 #2
Hi Group,

Yes it appears to be becuase the of the thread. Confusing for those
trying to understand and use threads in C# and .NET.

Please find attached the modified version I was talking about that
works without the thread.

Why does the above code report incorrect the connection succeed when
you start the connect request in a sepearte thread?

What mod for my interest would need to be make to have the above code
that is started via thread.start to report the same as the below code?

connectHost Started
connectHost Complete
connectHostCall back Started
connectHostCall back Socket Failed to Connect

Thanks

Mark
using System;
using System.Collecti ons.Generic;
using System.Text;
using System.Threadin g;
using System.Net;
using System.Net.Sock ets;
using System.IO;

namespace ASYNC
{
class Program
{
static void Main(string[] args)
{
ConnectionClass client = new ConnectionClass ();
// Thread firstThread = new Thread(new
ThreadStart(cli ent.connectHost ));
// firstThread.Nam e = "Client";
// firstThread.Sta rt();
client.connectH ost();
Thread.Sleep(50 000);
}
}

public class ConnectionClass
{
private static Socket socketHost;

public ConnectionClass ()
{
socketHost = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p);
}

private void connectHostCall back(IAsyncResu lt asyncResult)
{
Console.WriteLi ne("connectHost Callback Started");
Socket sock = (Socket)asyncRe sult.AsyncState ;

try
{
sock.EndConnect (asyncResult);
Console.WriteLi ne("connectHost Callback Socket
Connected");
}
catch
{
Console.WriteLi ne("connectHost Callback Socket Failed
to Connect");
}
}

public void connectHost()
{
Console.WriteLi ne("connectHos t Started");
IPEndPoint remoteServerEnd Point = new
IPEndPoint(IPAd dress.Parse("19 2.168.1.10"), 8888);
AsyncCallback asyncConnectHos t = new
AsyncCallback(c onnectHostCallb ack);
IAsyncResult statusConnect =
socketHost.Begi nConnect(remote ServerEndPoint, asyncConnectHos t,
socketHost);
Console.WriteLi ne("connectHos t Complete");
}
public class StateObject
{
public Socket stateSocket = null;
public const int BufferSize = 1500;
public byte[] buffer = new byte[BufferSize];
}
}
}

Mar 31 '07 #3
On Sat, 31 Mar 2007 13:11:45 -0700, <sh******@yahoo .com.auwrote:
[...]
Please find attached the modified version I was talking about that
works without the thread.
Where? You posted code, but it looks to me exactly like the first version
of the code you posted?
Why does the above code report incorrect the connection succeed when
you start the connect request in a sepearte thread?
I do not know. Obviously there's some sort of connection between the
AsyncResult and the thread that causes the async operation to complete as
soon as the thread exits. A cursory look at the .NET documentation didn't
show me anything that suggests why that would be the case and I can't
think of any reason off the top of my head that would justify that
behavior (after all, the callback is run on a different thread anyway, so
why should it matter whether the thread that originally started the
operation is still around or not?).
What mod for my interest would need to be make to have the above code
that is started via thread.start to report the same as the below code?
As I said, I see no reason to use a thread at all. You gain nothing, at
least in the example code you've provided.

However, if you feel that you really need to use a thread, then you need
the thread to stay alive until the operation completes. The most obvious
solution there is to simply not use an async operation in the first
place. Just make it a synchronous operation and allow the thread to wait
until the operation has completed.

If you insist on using a thread even when you don't need one, and on top
of that insist on using the async pattern even when you don't need to,
then you can synchronize the thread you create with the operation by
creating a waitable event (eg AutoResetEvent) and using the WaitOne()
method on that event in the thread you create to make the thread pause at
that point. Then in your callback, after you're done processing the async
result, call the Set() method on the waitable event to release the thread
you previously created.

For example:

...

/* Create the waitable event, initialized to unsignaled */
private AutoResetEvent _evtCallback = new AutoResetEvent( false);

private void connectHostCall back(IAsyncResu lt asyncResult)
{
... /* processing code goes first */

/* Set (signal) the event */
_evtCallback.Se t();
}

public void connectHost()
{
... /* code to initiate async operation goes here */

/* Wait here until the event is signaled */
_evtCallback.Wa itOne();

Console.WriteLi ne("connectHos t Complete");
}

...

I reiterate: I do not see the need to create a new thread in the first
place. The only code that the thread executes happens basically
immediately and you only slow things down by creating a thread where the
code should run. Furthermore, if you insist on going to the effort to
create the thread, if you're going to just make the thread pause and wait
until the operation has completed then you should not bother making the
operation asynchronous in the first place; make it synchronous and let any
waiting that happens in the thread happen naturally by simply waiting for
the synchronous operation complete within the thread.

The implementation you've chosen appears to me to be about the least
efficient way you could have chosen.

Pete
Mar 31 '07 #4
Hi Pete,

Thanks for your reply. Your answer is exactly what I was lokking for
with the event information.

Yes I agree with your about the efficiency of the code, however that
was created to demonstrate the issue in a simple example.
I thought that was the easiest way to demonstrate the issue I was
observing.

Thanks. Off to read alot more about events.

Mark

Mar 31 '07 #5

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

Similar topics

2
1895
by: Gordon Messmer | last post by:
I've been working on a threaded daemon application to filter email. The source for the program is here: http://phantom.dragonsdawn.net/~gordon/courier-patches/courier-pythonfilter/ The daemon loads individual filters as modules and hands the names of the message and control files to each module in turn for processing. One of the modules (filters/dialback.py) checks the address of the sender, connects to the MX servers for the senders...
5
23358
by: Parahat Melayev | last post by:
I am trying to writa a multi-client & multi-threaded TCP server. There is a thread pool. Each thread in the pool will handle requests of multiple clients. But here I have a problem. I find a solution but it is not how it must be... i think. When threads working without sleep(1) I can't get response from server but when I put sleep(1) in thread function as you will see in code, everything works fine and server can make echo nearly for...
1
5228
by: Jim P. | last post by:
I'm having trouble returning an object from an AsyncCallback called inside a threaded infinite loop. I'm working on a Peer2Peer app that uses an AsyncCallback to rerieve the data from the remote peer. I have no problem connecting the peers and streaming Network Streams. When the incoming data is finished recieving, I act upon it. This works great as long as all of the code is inside my form. I want to build the networking code into a...
4
18136
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.
0
367
by: Tomasz Naumowicz | last post by:
Hello Everybody, I have the following problem with sockets. Socket.Available reports data in the buffer (e.g. 1849 bytes) but Socket.Read throws an exception because the connection is already closed. How do I get the data from the buffer? background: I open multiple connections to my Windows 2003 Web Server (simple HTTP GET).
18
64442
by: nephish | last post by:
lo there, i have a simple app that connects to a socket to get info from a server i looks like this serverhost = 'xxx.xxx.xxx.xxx' serverport = 9520 aeris_sockobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM) aeris_sockobj.connect((serverhost,serverport))
1
17552
by: Mr. Beck | last post by:
Hello, Please Help..... I have been working with some tcp/ip socket communication within a C# program recently. Basicly, I have a program (myProblemProgram) that has a socket connected to another program for information passing. Upon receiving a particular "command" from the the information passing program, myProblemProgram will launch a separate thread to do individual communication with another file transfer program. The thread...
6
2852
by: Sean | last post by:
Hi Everyone, My apologies for a somewhat dump question but I am really stuck. I have been working on this code for two days straight I am dont know what is wrong with it. when I run the code, All I get is Input: and the program quits. I also tried reading this online but I didn't quite get it. What is the diff between sin_addr and sin_addr.s_addr. My understanding is that the latter is the IP address of my machine where as the former is...
2
18381
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
9511
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
10200
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...
1
10139
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7529
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
6769
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5418
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
5551
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3701
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2909
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.