473,721 Members | 1,794 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Async socket connection ends up in Unable to read data from....

reposted with the right microsoft managed newsgroup ID: Sorry for the
inconvinience

Hi,

I've written a class for client-socket connection, but I get a lot of times
the error message "Unable to read data from the transport connection" when
restart reading the stream with socket.BeginRea d in the Sub
SocketIncomingM sg. I'm debugging now for weeks, but I can't detect where
it's
going wrong.

the part of code where it fails:

Try
RnetworkStream. BeginRead(myRec eivedData, 0,
myReceivedData. Length, New AsyncCallback(A ddressOf SocketIncomingM sg),
RnetworkStream)
Catch ex As Exception
'THIS ONE OFTEN FAILES
'UNABLE TO READ DATA FROM THE TRANSPORT CONNECTION
DisconnectSocke t()
End Try

Can someone please review my code and point me in the right direction. This
thing is driving me nuts..

The Complete code:

Imports System.Net.Sock ets
Imports System.Text
Imports System.Threadin g

Namespace TCPIP
Public Enum Status
Disconnected = 0
Listening = 1
Connected = 3
Connecting = 2
End Enum

Public Class TCPClientSock
Private mState As TCPIP.Status
Private mTcpClient As TcpClient
Private RnetworkStream As NetworkStream

Public Event DataReceived(By Val Data As String)
Public Event CommError(ByVal ErrorMessage As Exception)
Public Event StatusChanged(B yVal State As TCPIP.Status)

Private myReceivedData( ) As Byte

Public Sub New()
mState = TCPIP.Status.Di sconnected
RaiseEvent StatusChanged(m State)
End Sub
Public ReadOnly Property Connected() As Boolean
Get
Return (mState = Status.Connecte d)
End Get
End Property
Public Sub Shutdown()
Me.DisconnectSo cket()
End Sub
Public Function ConnectSocket(B yVal Server As String, ByVal Port As
Int16) As Boolean
Try
mTcpClient = Nothing
mTcpClient = New TcpClient
'make connection
mState = TCPIP.Status.Co nnecting
RaiseEvent StatusChanged(m State)
mTcpClient.Conn ect(Server, Port)
'connected
RnetworkStream = mTcpClient.GetS tream
If RnetworkStream. CanRead Then
mState = TCPIP.Status.Co nnected
ReDim myReceivedData( mTcpClient.Rece iveBufferSize)
'start reading stream
RnetworkStream. BeginRead(myRec eivedData, 0,
myReceivedData. Length, New AsyncCallback(A ddressOf SocketIncomingM sg),
RnetworkStream)
RaiseEvent StatusChanged(m State)
Return True
End If
Catch e As Exception ' error while connecting
RaiseEvent CommError(e)
'not connected
mState = TCPIP.Status.Di sconnected
RaiseEvent StatusChanged(m State)
Try
mTcpClient.Clos e()
Catch
End Try
End Try
End Function

Private Sub SocketIncomingM sg(ByVal arMsg As IAsyncResult)
Dim intCount As Integer
Dim lus As Int16
Dim myMessage As String = ""
Try
intCount = RnetworkStream. EndRead(arMsg)
If intCount < 1 Then
'socket closed
DisconnectSocke t()
End If
Catch ex As Exception

End Try
For lus = 0 To intCount - 1
myMessage &= Chr(myReceivedD ata(lus))
Next
'process message in background
ThreadPool.Queu eUserWorkItem(A ddressOf Me.ProcessRecei vedData,
CType(myMessage , Object))
'restart reading stream
Try
RnetworkStream. BeginRead(myRec eivedData, 0,
myReceivedData. Length, New AsyncCallback(A ddressOf SocketIncomingM sg),
RnetworkStream)
Catch ex As Exception
'THIS ONE OFTEN FAILES
'UNABLE TO READ DATA FROM THE TRANSPORT CONNECTION
DisconnectSocke t()
End Try
End Sub

Private Sub ProcessReceived Data(ByVal Data As Object)
If CStr(Data) <"" Then RaiseEvent DataReceived(CS tr(Data))
End Sub

Public Sub DisconnectSocke t()
Try
RnetworkStream. Close()
Catch ex As Exception
End Try
Try
mTcpClient.Clos e()
Catch ex As Exception
End Try
Try
mTcpClient = Nothing
Catch ex As Exception
End Try
mState = TCPIP.Status.Di sconnected
RaiseEvent StatusChanged(m State)
End Sub

Public Sub SendSocketData( ByVal Data As String)
Try
Dim SnetworkStream As NetworkStream = mTcpClient.GetS tream()
Dim sendBytes(Data. Length - 1) As Byte
Dim lus As Int16
For lus = 0 To Data.Length - 1
sendBytes(lus) = Asc(Data.Substr ing(lus, 1))
Next
SnetworkStream. Write(sendBytes , 0, sendBytes.Lengt h)
Catch e As Exception
RaiseEvent CommError(e)
End Try
End Sub
End Class
Public Class TCPServerSock
'removed due to irrelevance
End Class
End Namespace
Sep 7 '06 #1
5 15723
Hi,

From your description, when you use the the code you provided in your
application, the code that below will generate the error as below.
"Unable to read data from the transport connection"

The occurred when the SocketIncomingM sg method is reentry after the first
reading operating finished.

Here is the make a simple test for your code, but I can not reproduce the
problem.
[Server]
Imports System
Imports System.Net.Sock ets
Imports System.Text

Public Class TcpTimeServer

Private Const portNum As Integer = 13

Public Overloads Shared Function Main(ByVal args() As [String]) As
Integer
Dim done As Boolean = False

Dim listener As New TcpListener(por tNum)

listener.Start( )

While Not done
Console.Write(" Waiting for connection...")
Dim client As TcpClient = listener.Accept TcpClient()

Console.WriteLi ne("Connection accepted.")
Dim ns As NetworkStream = client.GetStrea m()

Dim byteTime As Byte() = _
Encoding.ASCII. GetBytes(DateTi me.Now.ToString ())

Try
ns.Write(byteTi me, 0, byteTime.Length / 2)
System.Threadin g.Thread.Sleep( 3000)
ns.Write(byteTi me, byteTime.Length / 2, byteTime.Length / 2)
ns.Close()
client.Close()
Catch e As Exception
Console.WriteLi ne(e.ToString() )
End Try
End While

listener.Stop()

Return 0
End Function 'Main
End Class 'TcpTimeServer

[Client]
Public Class Form1
Dim WithEvents c As TCPIP.TCPClient Sock

Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles Button1.Click
c = New TCPIP.TCPClient Sock()
If c.ConnectSocket ("machinenam e", 13) Then
MsgBox("Connect ed")
End If
End Sub

Private Sub c_DataReceived( ByVal Data As String) Handles c.DataReceived
MsgBox(Data)
End Sub
End Class

You may have a try and let me know if the code above will reproduce the
problem at your side.

I look forward to hearing from you.

Also I suggest try to check the RnetworkStream. CanRead in method
SocketIncomingM sg, just as you do in the method ConnectSocket.
Best regards,

Peter Huang

Microsoft Online Community Support
=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Sep 8 '06 #2
Peter,

the code you send me works just fine..

To clear out more specific on my problem, The error doesn't occur after the
first read operation is finished, as far as I can see, it's completely
random (it should have a reason, but I can't track it down) Sometimes it's
after the 4th read operation, sometimes it's after the 500th read operation,
sometime it's after the ... read operation. In other words, sometimes it
fails after 5 minutes, sometimes after 1 hour, sometimes after 1 day.

In my application, the socket-connection stays connected 24/7 (it least it
should do so), at least every 15 minutes I will receive some data from the
server, sometimes less as 15 minutes.

The socket connection will use a gprs connection to the server, so some
small latency can occur, but i think the OS should take care of this... (Is
this right?)

What reason can there be that this error occurs when

RnetworkStream. BeginRead(myRec eivedData, 0, myReceivedData. Length, New
AsyncCallbackAd dressOf SocketIncomingM sg),RnetworkStr eam)

Is it possible that a networkstream 'suddenly' becomes 'unreadable' so that
I have to check RnetworkStream. CanRead every time when doing the .BeginRead?

What to do when .CanRead = False, can the stream become readable again after
some time? I don't want to reconnect my socket everytime to the server
again. If it can recover, how to do so.

On the server-side, the socket is still connected when the client fails the
..BeginRead

This thing is driving me nuts....

Kind regards,
Arno Broeders
Sep 8 '06 #3
Hi Arno,

It is hard to guess what is the root cause the scenario without reproduce
the problem.
From the description, I understand the Exception throw is IOException.

But from the MSDN doucment in the scenario below, the IOException may be
thrown when the NetworkStream.B eginRead
IOException
The underlying Socket is closed.
-or-
There was a failure while reading from the network.
-or-
An error occurred when accessing the socket. See the Remarks section for
more information.

Note
If you receive an IOException, check the InnerException property to
determine if it was caused by a SocketException . If so, use the ErrorCode
property to obtain the specific error code, and refer to the Windows
Sockets version 2 API error code documentation in MSDN for a detailed
description of the error.

NetworkStream.B eginRead Method
http://msdn2.microsoft.com/en-us/lib...tworkstream.be
ginread.aspx

So I think you may try to print out the detailed Exception/InnerException
information as below.
Try
Catch ex As Exception
Debug.Print(ex. ToString())
Debug.Print(ex. InnerException. ToString())
DisconnectSocke t()
End Try
Also please check all the code in both Server and Client about close
socket/connection.
Because you can not reproduce the problem with my server code, you may try
to add Log code line before every socket related call.
e.g.
Debug.Print "Socket accept"
Debug.Print "Socket read"
Debug.Print "Socket close"

To monitor if there is any possibility that the socket is closed by server
side.

Here is the error list may occur in the Win32 ErrorCode.
http://msdn.microsoft.com/library/de...us/winsock/win
sock/recv_2.asp
or
the path to the C++ header Winsock2.h
e.g.<this may differ based on your installation>
C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\Include

Best regards,

Peter Huang

Microsoft Online Community Support
=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Sep 11 '06 #4
Okay, I implemented the logging in my application and found 2 reasons for
errors.

14-9-2006 10:18:14 - System.IO.IOExc eption: Unable to read data from the
transport connection. ---System.Net.Sock ets.SocketExcep tion: An existing
connection was forcibly closed by the remote host
at System.Net.Sock ets.Socket.Begi nReceive(Byte[] buffer, Int32 offset,
Int32 size, SocketFlags socketFlags, AsyncCallback callback, Object state)
at System.Net.Sock ets.NetworkStre am.BeginRead(By te[] buffer, Int32
offset, Int32 size, AsyncCallback callback, Object state)
--- End of inner exception stack trace ---
at System.Net.Sock ets.NetworkStre am.BeginRead(By te[] buffer, Int32
offset, Int32 size, AsyncCallback callback, Object state)
at
DataCollectorSe rvice.TCPIP.TCP ClientSock.Sock etIncomingMsg(I AsyncResult
arMsg) in
S:\VS.2003\Proj ects\iView\Part ialCollectors\O MRON-Collector\ClsTC PIP.vb:line
86
14-9-2006 10:18:14 - System.Net.Sock ets.SocketExcep tion: An existing
connection was forcibly closed by the remote host
at System.Net.Sock ets.Socket.Begi nReceive(Byte[] buffer, Int32 offset,
Int32 size, SocketFlags socketFlags, AsyncCallback callback, Object state)
at System.Net.Sock ets.NetworkStre am.BeginRead(By te[] buffer, Int32
offset, Int32 size, AsyncCallback callback, Object state)

This one is strange because the socket on the server was still opened. Maybe
it's my 3com internet NAT-router that will close socket connections that
stay open for a long time. Can this be?

Second error is:

14-9-2006 9:35:22 - System.ObjectDi sposedException : Cannot access a disposed
object named "System.Net.Soc kets.NetworkStr eam".
Object name: "System.Net.Soc kets.NetworkStr eam".
at System.Net.Sock ets.NetworkStre am.BeginRead(By te[] buffer, Int32
offset, Int32 size, AsyncCallback callback, Object state)
at
DataCollectorSe rvice.TCPIP.TCP ClientSock.Sock etIncomingMsg(I AsyncResult
arMsg) in
S:\VS.2003\Proj ects\iView\Part ialCollectors\O MRON-Collector\ClsTC PIP.vb:line
86

This one is bugging me the most.. How can it be that .EndRead on the stream
is succesfull and when doing a new .BeginRead the stream is suddenly
disposed.

Peter can you please advise me?

Kind regards,
Arno

""Peter Huang" [MSFT]" <v-******@online.m icrosoft.comsch reef in bericht
news:j6******** *****@TK2MSFTNG XA01.phx.gbl...
Hi Arno,

It is hard to guess what is the root cause the scenario without reproduce
the problem.
From the description, I understand the Exception throw is IOException.

But from the MSDN doucment in the scenario below, the IOException may be
thrown when the NetworkStream.B eginRead
IOException
The underlying Socket is closed.
-or-
There was a failure while reading from the network.
-or-
An error occurred when accessing the socket. See the Remarks section for
more information.

Note
If you receive an IOException, check the InnerException property to
determine if it was caused by a SocketException . If so, use the ErrorCode
property to obtain the specific error code, and refer to the Windows
Sockets version 2 API error code documentation in MSDN for a detailed
description of the error.

NetworkStream.B eginRead Method
http://msdn2.microsoft.com/en-us/lib...tworkstream.be
ginread.aspx

So I think you may try to print out the detailed Exception/InnerException
information as below.
Try
Catch ex As Exception
Debug.Print(ex. ToString())
Debug.Print(ex. InnerException. ToString())
DisconnectSocke t()
End Try
Also please check all the code in both Server and Client about close
socket/connection.
Because you can not reproduce the problem with my server code, you may try
to add Log code line before every socket related call.
e.g.
Debug.Print "Socket accept"
Debug.Print "Socket read"
Debug.Print "Socket close"

To monitor if there is any possibility that the socket is closed by server
side.

Here is the error list may occur in the Win32 ErrorCode.
http://msdn.microsoft.com/library/de...us/winsock/win
sock/recv_2.asp
or
the path to the C++ header Winsock2.h
e.g.<this may differ based on your installation>
C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\Include

Best regards,

Peter Huang

Microsoft Online Community Support
=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no
rights.

Sep 14 '06 #5
Hi Arno,

Thanks very much for your efforts and information.

From your information, you will encounter two exceptions.
1. System.IO.IOExc eption: Unable to read data from the transport
connection. ---System.Net.Sock ets.SocketExcep tion: An existing connection
was forcibly closed by the remote host

As the error description, this means the underlying socket is closed by
remote host. But due to the complex in network environment this may be
caused by many possibility. Your assumption also may be one of the
possibility. Because the network path between your machine A and the Server
B may include many other network devices, e.g. Router, Proxy, Firewall.....

2. System.ObjectDi sposedException : Cannot access a disposed
object named "System.Net.Soc kets.NetworkStr eam".

From the error, the networkstream is disposed. But we are still trying to
access to it. So far it is hard to guess what is the root cause. A possible
cause it that after the End Read, the underlying socket may be closed, so
the networkstream is disposed too and then we are trying to access it so
get the exception.

Since so far you can not reproduce the problem with the simple server code
I send to you.

I suggest you try to run your Server and Client code on two directly
connect machines or even one machine, if there are no error occur for a
long time e.g. one week. We should consider your code is OK but is not
robust and error handling enough.

Commonly network application will need more error handling than common
application, especially the wireless network environment. A common way is
to handle all the possible exception and do proper action, so that we can
built a robust application.
BTW: for such GRPS network, I understand it is low bandwidth network and
not very relialbe(it may be disconnected due to gprs signals) compared to
LAN, I suggest you sent a small data in one time so that a End Read will
finish more quick.
e.g.
If the socket is closed, we may try to reconnect to the server and try a
predefined time to write error log. This depends on concrete implement
policy.
The main idea is to retry when error occurred, and retry a few times to
reconnect or event report error to End User and stop doing.
Just as IE, when we are trying to connect to a web site, when it has gone
through its error handle steps, it will show an error page to End User.

If you still have any concern, please feel free to let me know.
I look forward to hearing from you.

Best regards,

Peter Huang
Microsoft Online Partner Support

When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== ========
Business-Critical Phone Support (BCPS) provides you with technical phone
support at no charge during critical LAN outages or "business down"
situations. This benefit is available 24 hours a day, 7 days a week to all
Microsoft technology partners in the United States and Canada.
This and other support options are available here:
BCPS:
https://partner.microsoft.com/US/tec...rview/40010469
Others: https://partner.microsoft.com/US/tec...pportoverview/

If you are outside the United States, please visit our International
Support page: http://support.microsoft.com/common/international.aspx.
=============== =============== =============== ========
This posting is provided "AS IS" with no warranties, and confers no rights.

Sep 15 '06 #6

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

Similar topics

2
497
by: brendonlam | last post by:
Hi there, Hoping someone could advise me here pls; I'm creating a C# class that implements a telnet client socket allowing a VB . NET application to communicate with telnet servers. After leaving the app running for just 6 hrs, the thread count exploded to close to 1000, before the app finally stops responding. The handles probably hit close to 10000. Tracing my code, I isolated the leak to when I execute a telnet command. Everytime I...
5
11713
by: mscirri | last post by:
The code below is what I am using to asynchronously get data from a PocketPC device. The data comes in fine in blocks of 1024 bytes but even when I send no data from the PocketPC constant blocks of 1024 with all values set to Null arrive. Other than examine a block of 1024 to see if the entire block is null, is there any other way to determine if , say a chat message "Hi Charlie" has been received completely?
0
2087
by: whizpop | last post by:
Hi, First of all, thanks for a great starter kit, now If I could just get it to work (fully). I am trying to compile and run the solution/services all on a local dev box. I am able to successfully run most of the SampleApp features (Register,Feedback,Error report, version check) The only method I can not execute is the BuyNow example. I have tried leveraging the Sharewarestarterkit.com web service to rule out locality, to no avail.
6
3818
by: Shak | last post by:
Hi all, Three questions really: 1) The async call to the networkstream's endread() (or even endxxx() in general) blocks. Async calls are made on the threadpool - aren't we advised not to cause these to block? 2) You can connect together a binaryreader to a networkstream:
7
2857
by: Shak | last post by:
Hi all, I'm trying to write a thread-safe async method to send a message of the form (type)(contents). My model is as follows: private void SendMessage(int type, string message) { //lets send the messagetype via async NetworkStream ns = client.GetStream(); //assume client globally accessible
0
4750
by: phplasma | last post by:
Hey, I am currently attempting to implement a multi-threaded C# socket, using SSL (.pem file/certification/private key combo) server using Visual Studio C# Express. I have successfully made the client application establish a connection, and send data, which appears in plain, de-crypted text on the server - this works.
0
679
by: Arno | last post by:
Hi, I've written a class for client-socket connection, but I get a lot of times the error message "Unable to read data from the transport connection" when restart reading the stream with socket.BeginRead in the Sub SocketIncomingMsg. I'm debugging now for weeks, but I can't detect where it's going wrong. the part of code where it fails:
11
8609
by: atlaste | last post by:
Hi, In an attempt to create a full-blown webcrawler I've found myself writing a wrapper around the Socket class in an attempt to make it completely async, supporting timeouts and some scheduling mechanisms. I use a non-blocking approach for this, using the call to 'poll' to support the async mechanism - rather than the 'begin' and 'end' functions. I already found that connecting doesn't set the "isconnected" variable correctly...
3
2685
by: Ryan Liu | last post by:
Will TcpClient.GetStream().Read()/ReadByte() block until at least one byte of data can be read? In a Client/Server application, what does it mean at the end of stream/no more data available? Client could send data once few seconds of minutes. Is there an "end" at all? In a C/S application, if server side call BeginginRead() again in EndRead() to create a endless loop to get message from client, is this a better approach than "one...
1
20634
by: Ryan Liu | last post by:
Hi, I have a 100 clients/ one server application, use ugly one thread pre client approach. And both side user sync I/O. I frequently see the error on server side(client side code is same, but I don't see the error): "System.IO.IOException: Unable to read data from the transport connection:A blocking operation was interrupted by a call to WSACancelBlockingCall"
0
8837
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8728
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
9366
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
9214
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
9059
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...
1
6668
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
5977
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();...
2
2572
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2129
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.