MSDN Using Asynchronous Server Socket ?


G

Guest

I am using the code of "MSDN-Using Asynchronous Server Socket"
"ms-help://MS.VSCC.2003/MS.MSDNQTR.2004JUL.1033/cpguide/html/cpconnon-blockingserversocketexample.htm"

Here

try {
listener.Bind(localEndPoint);
listener.Listen(100);

while (true) {
// Set the event to nonsignaled state.
allDone.Reset();

// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept( new
AsyncCallback(AcceptCallback),listener );
// Wait until a connection is made before continuing.
allDone.WaitOne();
}

Why we use

ManualResetEvent allDone = new ManualResetEvent(false);

and call allDone.Reset() every time.

and why not we use AutoResetEvent instead of ManualResetEvent. So not call
Reset method every time.

Any Reason ?.

Because when i use this code in my real application as a window service,
after some time (1 day or more) it reject to accept new sockets but service
still running. This service installed on 20 machines which is connected via
modem. But the problem occured on one or two machines.

Error : No connection could be made because the target computer actively
refused it
Code : 10061 WSAECONNREFUSED
Please help me urgently.
Zeeshan Gulzar
 
Ad

Advertisements

C

# Cyrille37 #

Zeeshan said:
I am using the code of "MSDN-Using Asynchronous Server Socket".
"ms-help://MS.VSCC.2003/MS.MSDNQTR.2004JUL.1033/cpguide/html/cpconnon-blockingserversocketexample.htm"

Here

try {
listener.Bind(localEndPoint);
listener.Listen(100);

while (true) {
// Set the event to nonsignaled state.
allDone.Reset();

// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept( new
AsyncCallback(AcceptCallback),listener );
// Wait until a connection is made before continuing.
allDone.WaitOne();
}

Why we use

ManualResetEvent allDone = new ManualResetEvent(false);

and call allDone.Reset() every time.

and why not we use AutoResetEvent instead of ManualResetEvent. So not call
Reset method every time.

Any Reason ?.

Because when i use this code in my real application as a window service,
after some time (1 day or more) it reject to accept new sockets but service
still running. This service installed on 20 machines which is connected via
modem. But the problem occured on one or two machines.

Error : No connection could be made because the target computer actively
refused it
Code : 10061 WSAECONNREFUSED
Please help me urgently.
Zeeshan Gulzar
Look about implementing a override method like :

public override object InitializeLifetimeService()
{
return null;
}

I've to use it for remoting for the same problem, perhaps you need something
like that in you listening code.

Sorry to be so evasive.

cyrille
 
M

Michael D. Ober

I had a similar problem. The solution I ended up with was to make my
clients smart enough to reconnect on connection failure and then implement a
connection timeout. Remember that in .NET, you apparently cannot use the
framework to create a single threaded IP server, so you must deal with
interthread critical sections as each IP connection gets it's own thread.
As for the questions about number of connections and Exceptions in the
AcceptCallback, my answer was "unknown - possibly multiple per employee in
the company" and "my AcceptCallback" call wasn't inside an exception handler
and the application would have crashed had there been any.

Here's my code:

'============================================
Option Compare Text
Option Strict On
Option Explicit On

Imports System.Net.Sockets
Imports System.Net
Imports System.Threading
Imports System.Text.ASCIIEncoding

Module IPMessageHandler
Private ClientConnected As New AutoResetEvent(False)

Public Sub CreateListener()
Dim ServerAddress As IPAddress =
Dns.GetHostEntry(My.Computer.Name).AddressList(0)
Dim LocalHost As New IPEndPoint(ServerAddress,
OSInterface.iniWrapper.ReadInt("Dialer", "Port", "Wakefield.ini"))
Dim tcpServer As New TcpListener(LocalHost)
tcpServer.Start()
WriteLog("Ready for IP Connections")
Do
tcpServer.BeginAcceptSocket(AddressOf AcceptRequest, tcpServer)
Debug.Print("Waiting for a connection")
ClientConnected.WaitOne()
Loop
End Sub

Private Sub AcceptRequest(ByVal ar As System.IAsyncResult)
Dim sock As Socket = Nothing
Dim ClientEndPoint As New IPEndPoint(0, 0)
Dim ClientName As String = ""
Dim MsgIn As String = ""
Dim BytesIn(1024) As Byte
Dim i As Integer

Try
Debug.Print("Incoming Connection")
Dim Listener As TcpListener = CType(ar.AsyncState, TcpListener)
sock = Listener.EndAcceptSocket(ar)
ClientEndPoint = CType(sock.RemoteEndPoint, IPEndPoint)
ClientName = ClientEndPoint.Address.ToString
ClientName = Dns.GetHostEntry(ClientName).HostName
ClientName &= ":" & ClientEndPoint.Port.ToString
ClientConnected.Set()

' If the socket remains unused for 5 minutes, error out and release
server resources
If Not ClientName.Contains("Lily_Tomlin") Then sock.ReceiveTimeout = 5
* 60 * 1000
Do
Dim BytesReceived As Integer = sock.Receive(BytesIn)
Select Case BytesReceived
Case 0
Exit Do
Case Else
MsgIn &= ASCII.GetString(BytesIn, 0, BytesReceived)
i = InStr(MsgIn, EOL)
Do While i > 0
Dim msg As String = Left$(MsgIn, i - 1)
MsgIn = Mid$(MsgIn, i + 1)
Dim msgOut As String = ProcessMessage(msg)
If msgOut <> "" Then
Dim BytesOut() As Byte = ASCII.GetBytes(msgOut & EOL)
sock.Send(BytesOut)
End If
i = InStr(MsgIn, EOL)
Loop
End Select
Loop

Catch ex As Exception
WriteLog(ex.Message)
Finally
sock.Shutdown(SocketShutdown.Both)
sock.Close()
End Try
End Sub

Private Function ProcessMessage(ByVal msg As String) As String
Dim msgReturn As String = ""
Return msgReturn
End Function

End Module
'====================================
Mike.

Vadym Stetsyak said:
Hello, Zeeshan!

How many connections must the service accept?
Are you sure that there were no exceptions in AcceptCallback?

IIRC in that example in AcceptCallback the call to BeginReceive is made.
Are there any exceptions in the BeginReceive delegate.
allDone.Set() is called after the read is completed, maybe service is
hanging on ReceiveData thus introducing deadlock for the accept thread?
 
G

Guest

I am using MSDN Sample Code of "Using Asynchronous Server Socket (C#)" in a
windows service running
under Local System Account named Listener Service.

Client Code is also Asynchronous(C#) and embed in Windows Service running
under Local System Account
named Dispatcher Service.

This service works as follows:

1. Get message from Message Queue (MSMQ)
2. Connect to server at port 4000 (This machine is connected with server
machine via Modem
Both Start "Routing and Remote Access Service" just before Listener &
Dispatcher Services starts).
3. Send Message to server and close the socket immediately (Not set Linger
option. default setting used)
4. When client connected with server, server get Socket from ENDAccept(),
store in State class etc.
(Complete code is from MSDN Sample Code mentioned above.)
5. Server Received the message and close the socket immediately (Default
Setting of socket is used).

Problem is here:

After about an hour, server reject to accept new sockets. Netstat -a -p tcp
shows the port 4000 is in
listening state. Client receive Error WSACONNREFUSED.

One thing is that according to MSDN, this problem (Client received
WSACONNREFUSED while server is listening)
occured due to queue of the server is full (backlog). I set backlog of the
socket with 10 using
"socket.listen(10);". But why queue is full, because i receive message from
socket and close it immediately
so this sould returned back to queue. I increase this value to 100 instead
of 10 but problem is still there.
I am using Windows Server 2000.

Is this is the problem of TIME_WAIT. There is no entry of TcpTimedWaitDelay
in my registry.
Accoring to MSDN, this entry exist at
HKEY_LOCAL_MACHINE\System\CurrectControlSet\services\Tcpip\Parameters
Please help me in this regard.

Or could i cope this problem by set linger option of socket to 10 sec or
less. Please help me in this regard also.

Thanks in advance.
 
M

Michael D. Ober

The problem is in your server code that handles the active connection. The
framework doesn't handle a lot of "idle" connections very well. When your
client disconnects, do you shutdown and then close the client socket?

Mike Ober.


Zeeshan Gulzar said:
I am using MSDN Sample Code of "Using Asynchronous Server Socket (C#)" in a
windows service running
under Local System Account named Listener Service.

Client Code is also Asynchronous(C#) and embed in Windows Service running
under Local System Account
named Dispatcher Service.

This service works as follows:

1. Get message from Message Queue (MSMQ)
2. Connect to server at port 4000 (This machine is connected with server
machine via Modem
Both Start "Routing and Remote Access Service" just before Listener &
Dispatcher Services starts).
3. Send Message to server and close the socket immediately (Not set Linger
option. default setting used)
4. When client connected with server, server get Socket from ENDAccept(),
store in State class etc.
(Complete code is from MSDN Sample Code mentioned above.)
5. Server Received the message and close the socket immediately (Default
Setting of socket is used).

Problem is here:

After about an hour, server reject to accept new sockets. Netstat -a -p tcp
shows the port 4000 is in
listening state. Client receive Error WSACONNREFUSED.

One thing is that according to MSDN, this problem (Client received
WSACONNREFUSED while server is listening)
occured due to queue of the server is full (backlog). I set backlog of the
socket with 10 using
"socket.listen(10);". But why queue is full, because i receive message from
socket and close it immediately
so this sould returned back to queue. I increase this value to 100 instead
of 10 but problem is still there.
I am using Windows Server 2000.

Is this is the problem of TIME_WAIT. There is no entry of TcpTimedWaitDelay
in my registry.
Accoring to MSDN, this entry exist at
HKEY_LOCAL_MACHINE\System\CurrectControlSet\services\Tcpip\Parameters
Please help me in this regard.

Or could i cope this problem by set linger option of socket to 10 sec or
less. Please help me in this regard also.

Thanks in advance.
 
G

Guest

Micheal Thanks,
I properly shutdown the socket after receiving the message.
socket.Shutdown(ShutdownType.Both);
socket.Close();


Michael D. Ober said:
The problem is in your server code that handles the active connection. The
framework doesn't handle a lot of "idle" connections very well. When your
client disconnects, do you shutdown and then close the client socket?

Mike Ober.
 
M

Michael D. Ober

Can you post the code that handles the socket accept and then the client
connection? I just went through this exercise (ported a TCP Server from
VB6) and had to work around a bug in the framework dealing with multiple
sockets. The raw WINSOCK API in Windows doesn't have this problem, thus my
feeling that this is a bug in the framework.

Mike Ober.



Zeeshan Gulzar said:
Micheal Thanks,
I properly shutdown the socket after receiving the message.
socket.Shutdown(ShutdownType.Both);
socket.Close();
 
G

Guest

Michael Thanks for your reply.

I mentioned earlier that i am using msdn "using asynchronous server socket"
example code as it is in a class library which is called from windows
service. and "using asynchronous client socket" for client service.
 
Ad

Advertisements

Joined
Apr 8, 2012
Messages
1
Reaction score
0
is this problem solved?I have same issue .
Socket server just works fine for some days but all of sudden it stops accepting new connections.On client I see connection refused error.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top