473,788 Members | 2,676 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

tcpclient problem

Hi,
I am using a tcpclient and a tcplistener to send and receive packets. The
client sends a packet and the listener replies with another one. I can send
2 packets and get an answer from the listener but it fails to send a third
packet. I don't get any error messages. The client sends the packet
successfully but it never arrives to the listener. This only happens when I
send the packets one straight after the other. If I place a delay of 2 sec
between each transition all packets will be received successfully.

This is how I read the buffer stream:
-----------------------------------------------------------------------
Private Sub ReceiveData(ByV al ar As IAsyncResult)

SyncLock tcpclient.GetSt ream

CountBytesRead = tcpclient.GetSt ream.EndRead(ar )

End SyncLock

MeamoryStream.W rite(readBuffer , 0, BytesRead)

...

SyncLock tcpclient.GetSt ream

tcpclient.GetSt ream.BeginRead( readBuffer, 0,
tcpclient.Recei veBufferSize, AddressOf ReceiveData, Nothing)

End SyncLock

End Sub

-------------------------------------------------------------------

I assume that the third packet has already arrived before
tcpClient.GetSt ream.BeginRead is invoked but I cannot see why this should be
a problem.

If anyone can advise me on that please do.

Thanks
Jul 21 '05 #1
2 7961
The EndRead method completes the asynchronous read operation started in the
BeginRead <frlrfsystemnet socketsnetworks treamclassbegin readtopic.htm>
method.
Before calling BeginRead, you need to create a callback method that
implements the AsyncCallback <frlrfsystemasy nccallbackclass topic.htm>
delegate. This callback method executes in a separate thread and is called
by the system after BeginRead returns. The callback method must accept the
IAsyncResult <frlrfsystemias yncresultclasst opic.htm> returned from the
BeginRead method as a parameter.
Within the callback method, call the AsyncState
<frlrfsystemias yncresultclassa syncstatetopic. htm> method of the IAsyncResult
to obtain the state object passed to the BeginRead method. Extract the
receiving NetworkStream <frlrfsystemnet socketsnetworks treamclasstopic .htm>
from this state object. After obtaining the NetworkStream, you can call the
EndRead method to successfully complete the read operation and return the
number of bytes read.
The EndRead method will block until data is available. The EndRead method
will read as much data as is available up to the number of bytes specified
in the size parameter of the BeginRead method. If the remote host shuts down
the Socket <frlrfsystemnet socketssocketcl asstopic.htm> connection and all
available data has been received, the EndRead method will complete
immediately and return zero bytes.
To obtain the received data, call the AsyncState method of the IAsyncResult,
and extract the buffer contained in the resulting state object.
Note If you receive a IOException <frlrfsystemioi oexceptionclass topic.htm>
check the InnerException <frlrfsystemexc eptionclassinne rexceptiontopic .htm>
property to determine if it was caused by a SocketException
<frlrfsystemnet socketssocketex ceptionclasstop ic.htm>. If so, use ErrorCode
<frlrfsystemnet socketssocketex ceptionclasserr orcodetopic.htm > to obtain the
specific error code. Once you have obtained this code, you can refer to the
Windows Socket Version 2 API error code documentation in MSDN for a detailed
description of the error.
Example
[Visual Basic, C#, C++] In the following example, myReadCallback is provided
to BeginRead <frlrfsystemnet socketsnetworks treamclassbegin readtopic.htm> as
the callback method. EndRead is implemented in myReadCallback to complete
the asynchronous read call started by BeginRead.
[Visual Basic]
Public Shared Sub myReadCallBack( ar As IAsyncResult)

Dim myNetworkStream As NetworkStream = CType(ar.AsyncS tate,
NetworkStream)
Dim myReadBuffer(10 24) As Byte
Dim myCompleteMessa ge As [String] = ""
Dim numberOfBytesRe ad As Integer

numberOfBytesRe ad = myNetworkStream .EndRead(ar)
myCompleteMessa ge = [String].Concat(myCompl eteMessage,
Encoding.ASCII. GetString(myRea dBuffer, 0, numberOfBytesRe ad))

' message received may be larger than buffer size so loop through until
you have it all.
While myNetworkStream .DataAvailable

myNetworkStream .BeginRead(myRe adBuffer, 0, myReadBuffer.Le ngth, New
AsyncCallback(A ddressOf
NetworkStream_A Sync_Send_Recei ve.myReadCallBa ck), myNetworkStream )
End While
' Print out the received message to the console.
Console.WriteLi ne(("You received the following message : " +
myCompleteMessa ge))
End Sub 'myReadCallBack

'Entry point which delegates to C-style main Private Function
Public Overloads Shared Sub Main()
Main(System.Env ironment.GetCom mandLineArgs())
End Sub
[C#]

public static void myReadCallBack( IAsyncResult ar ){

NetworkStream myNetworkStream = (NetworkStream) ar.AsyncState;
byte[] myReadBuffer = new byte[1024];
String myCompleteMessa ge = "";
int numberOfBytesRe ad;

numberOfBytesRe ad = myNetworkStream .EndRead(ar);
myCompleteMessa ge =
String.Concat(m yCompleteMessag e,
Encoding.ASCII. GetString(myRea dBuffer, 0, numberOfBytesRe ad));

// message received may be larger than buffer size so loop through until
you have it all.
while(myNetwork Stream.DataAvai lable){

myNetworkStream .BeginRead(myRe adBuffer, 0, myReadBuffer.Le ngth,
new
AsyncCallback(N etworkStream_AS ync_Send_Receiv e.myReadCallBac k),
myNetworkStream );

}

// Print out the received message to the console.
Console.WriteLi ne("You received the following message : " +
myCompleteMessa ge);
}
[C++]
static void myReadCallBack( IAsyncResult* ar) {
NetworkStream* myNetworkStream =
__try_cast<Netw orkStream*>(ar->AsyncState);
Byte myReadBuffer[] = new Byte[1024];
String* myCompleteMessa ge = S"";
int numberOfBytesRe ad;

numberOfBytesRe ad = myNetworkStream->EndRead(ar);
myCompleteMessa ge =
String::Concat( myCompleteMessa ge,
Encoding::ASCII->GetString(myRe adBuffer, 0, numberOfBytesRe ad));

// message received may be larger than buffer size so loop through until
you have it all.
while (myNetworkStrea m->DataAvailabl e) {
AsyncCallback* pasync = new AsyncCallback(0 , &myReadCallBack );
myNetworkStream->BeginRead(myRe adBuffer, 0, myReadBuffer->Length,
pasync,
myNetworkStream );
}

// Print out the received message to the console.
Console::WriteL ine(S"You received the following message : {0}",
myCompleteMessa ge);
}
[JScript] No example is available for JScript. To view a Visual Basic, C#,
or C++ example, click the Language Filter button in the upper-left corner of
the page.
Jul 21 '05 #2
Tnx for the reply,
however your example will not work for two reasons:

1. By placing the ReadBegin call into this while loop you allow the stream to be read only while bytes arrive at the port continuously. If there is a time gap between two data transmissions which practically means that NetworkStram.Da taVailable = False the code will not go inside the loop and therefore the ReadBegin will not start.

Suppose that 2000 bytes are sent to the port. The myReadCallBack sub will be called twice reading approximately 1000 bytes each time. At the second call though and after the stream has been read it will be empty and no data will be available. The while loop will not execute and the tcpclient will not listen to the port for incoming bytes.

Practically I was doing the same thing without having a loop based on the DataAvailable property.

2. By using the while loop you read the receive buffer until it is empty and then you convert the bytes to string and concatenate them. However I am not transmitting string objects but serialized classes, so even if this method worked I still couldn't use it because if I concatenate all the incoming bytes I will not be able to deserialize them later.

Here follows my exact ReadBuffer sub:

Private Sub ReceiveData(ByV al ar As IAsyncResult)
Try
Dim BytesRead As Integer
Dim Data As New IO.MemoryStream

SyncLock client.GetStrea m
BytesRead = client.GetStrea m.EndRead(ar)
End SyncLock

'Place the received bytes into a memorystream
'and raise an event to deserialize the stream
Data.Write(read Buffer, 0, BytesRead)
RaiseEvent DataReceived(Me , Data)

SyncLock client.GetStrea m
client.GetStrea m.BeginRead(rea dBuffer, 0, client.ReceiveB ufferSize,_
AddressOf ReceiveData, client.GetStrea m)
End SyncLock
Catch e As Exception
RaiseEvent ErrorOccured(e)
End Try
End Sub

Thanks
Ï <89*******@dskj fkdsfj.com> Ýãñáøå óôï ìÞíõìá news:vepTd.4893 0$wc.16395@trnd dc07...
The EndRead method completes the asynchronous read operation started in the
BeginRead <frlrfsystemnet socketsnetworks treamclassbegin readtopic.htm>
method.
Before calling BeginRead, you need to create a callback method that
implements the AsyncCallback <frlrfsystemasy nccallbackclass topic.htm>
delegate. This callback method executes in a separate thread and is called
by the system after BeginRead returns. The callback method must accept the
IAsyncResult <frlrfsystemias yncresultclasst opic.htm> returned from the
BeginRead method as a parameter.
Within the callback method, call the AsyncState
<frlrfsystemias yncresultclassa syncstatetopic. htm> method of the IAsyncResult
to obtain the state object passed to the BeginRead method. Extract the
receiving NetworkStream <frlrfsystemnet socketsnetworks treamclasstopic .htm>
from this state object. After obtaining the NetworkStream, you can call the
EndRead method to successfully complete the read operation and return the
number of bytes read.
The EndRead method will block until data is available. The EndRead method
will read as much data as is available up to the number of bytes specified
in the size parameter of the BeginRead method. If the remote host shuts down
the Socket <frlrfsystemnet socketssocketcl asstopic.htm> connection and all
available data has been received, the EndRead method will complete
immediately and return zero bytes.
To obtain the received data, call the AsyncState method of the IAsyncResult,
and extract the buffer contained in the resulting state object.
Note If you receive a IOException <frlrfsystemioi oexceptionclass topic.htm>
check the InnerException <frlrfsystemexc eptionclassinne rexceptiontopic .htm>
property to determine if it was caused by a SocketException
<frlrfsystemnet socketssocketex ceptionclasstop ic.htm>. If so, use ErrorCode
<frlrfsystemnet socketssocketex ceptionclasserr orcodetopic.htm > to obtain the
specific error code. Once you have obtained this code, you can refer to the
Windows Socket Version 2 API error code documentation in MSDN for a detailed
description of the error.
Example
[Visual Basic, C#, C++] In the following example, myReadCallback is provided
to BeginRead <frlrfsystemnet socketsnetworks treamclassbegin readtopic.htm> as
the callback method. EndRead is implemented in myReadCallback to complete
the asynchronous read call started by BeginRead.
[Visual Basic]
Public Shared Sub myReadCallBack( ar As IAsyncResult)

Dim myNetworkStream As NetworkStream = CType(ar.AsyncS tate,
NetworkStream)
Dim myReadBuffer(10 24) As Byte
Dim myCompleteMessa ge As [String] = ""
Dim numberOfBytesRe ad As Integer

numberOfBytesRe ad = myNetworkStream .EndRead(ar)
myCompleteMessa ge = [String].Concat(myCompl eteMessage,
Encoding.ASCII. GetString(myRea dBuffer, 0, numberOfBytesRe ad))

' message received may be larger than buffer size so loop through until
you have it all.
While myNetworkStream .DataAvailable

myNetworkStream .BeginRead(myRe adBuffer, 0, myReadBuffer.Le ngth, New
AsyncCallback(A ddressOf
NetworkStream_A Sync_Send_Recei ve.myReadCallBa ck), myNetworkStream )
End While


' Print out the received message to the console.
Console.WriteLi ne(("You received the following message : " +
myCompleteMessa ge))
End Sub 'myReadCallBack

'Entry point which delegates to C-style main Private Function
Public Overloads Shared Sub Main()
Main(System.Env ironment.GetCom mandLineArgs())
End Sub

Jul 21 '05 #3

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

Similar topics

3
9114
by: Daniel | last post by:
TcpClient close() method socket leak when i use TcpClient to open a connection, send data and close the TcpClient with myTcpClientInstance.Close(); it takes 60 seconds for the actual socket on the client machine to close per my network app the computer fills up w/ thousands of these :0 TCP foobox:8888 localhost:2188 TIME_WAIT :0 TCP foobox:8888 localhost:2189 TIME_WAIT :0 TCP foobox:8888 localhost:2190 TIME_WAIT
3
3050
by: מורדי | last post by:
Hi, I'm writing a client/server application in which the client send a series of screenshots to the server to be saved using the tcpclient. in most cases the first screenshot is transmitted ok and arrives at the server but from after that i only a couple of KB from the start of the file which cases the picture to display only the very top (of the screen). All the pictures are saved at the client side before sent to the server and they...
5
72307
by: Horst Walter | last post by:
What is wrong here? IPAddress ipAddress = IPAddress.Parse("10.10.20.1"); IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, this.port); this.tcpClient = new TcpClient(ipEndPoint); // PROBLEM HERE => Exception: "The requested address is not valid in its context" This works:
3
28655
by: Ricardo Quintanilla | last post by:
i had a problem whom i do not know how to explain. i was using a TcpClient (System.Net.Sockets.TcpClient) object to send and receive data to an AS400 socket. Two months ago it started to work slowly, about 4 seconds between send and receive. In our production environment with hundreds of transactions it was truly costly. a while ago i changed de TcpClient object. Now i am using a Socket (System.Net.Sockets.Socket) object and it...
0
1975
by: Torsten Brasch | last post by:
Hi All and Happy New Year ;) I have a very strange problem with System.Net.Sockets.TcpClient(). For some reason, the number of bytes I can receive is limited to 5460 bytes. I made sure that the server really sends everything I expect it to send. I am actually sending XML messages and this limit is a pain in the ... Here is the code: -------------------------------------------------------------------------- Dim tcpclient As New...
1
1741
by: Anders Berg | last post by:
Hi! I'm developing a very simple chat application in VB.NET and I've stumbled into a problem. For simplicity I'm using the TcpListener and TcpClient classes. However, at one point I discovered that I want to use the protected Active and Client properties of the TcpClient class. To do this I made my own derived class: Public Class MyTcpClient Inherits TcpClient
2
381
by: Theo | last post by:
Hi, I am using a tcpclient and a tcplistener to send and receive packets. The client sends a packet and the listener replies with another one. I can send 2 packets and get an answer from the listener but it fails to send a third packet. I don't get any error messages. The client sends the packet successfully but it never arrives to the listener. This only happens when I send the packets one straight after the other. If I place a delay of 2...
3
15533
by: Ryan Liu | last post by:
Hi, I use Server: Use an endless thread to lisiten to clients requests: while(true) { TcpClient client = myListener.AcceptTcpClient();
5
7323
by: puzzlecracker | last post by:
It looks like i need to get IPEndPoint first, but I cannot figure out from msdn the eventual obtainment of machine name and port number. Please suggest a solution. Thanks
0
9656
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
9967
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
8993
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
7517
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
6750
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
5399
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
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4070
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3674
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.