I have encountered with a most disturbing TCP problem:
I have cases (too many of them) that result in data loss.
Some inforamation on my test configuration:
I have to PC's which are the same (Dell Dimension 2400).
PC1 is the tcp server, PC2 is the tcp client, they two configured to 65535
bytes tco buffer/window, and working in synchronous manner while for each
client the server start a dedicated thread.
The client send the data size in the first block and this way the server
knows when to stop processing the data from this client by accumulating the
retuned valued from the Socket.Receive( ..) till it gets to the size received
in the first block.
When the server is handling a single client, no data is lost. But when I
switch the PC's so PC2 is the server and PC1 is the client, data is lost
causing the server to keep on waiting on the Socket.Receive( ..) while the
client is done.
When the server (on PC1) is handling several clients (multiple threads
generated in PC2) again data is lost and some of the clients data is missing
in the server side again causing the server to keep on waiting on the
Socket.Receive( ..) while all clients are done sending all their data.
I'm really don't know how fix that or what am I doing wrong.
Any advice will be more then welcome.
--------
Thanks
Sharon 5 6793
Sounds like you have some miscalculations or mistakes of that sort in
your application. I think it would help if you posted some more
important parts of your code or equivalent logic on how you are handling
multiple clients and things of that sort.
Ok, here is the code. I hope I didn't make any mistakes coping and cleaning
the code when posting it:
//////////////////////////////////////////////////////////////////////////
/// The TCP Client
//////////////////////////////////////////////////////////////////////////
int blockSize = 65535;
byte [] rowData = new byte[1048576];// 1 MByte
int blockCount = rowData.Length/blockSize + ((rowData.Lengt h % blockSize ==
0) ? 0 : 1);
IPEndPoint ep = new IPEndPoint(IPAd dress.Parse("Se rver IP"), 31001);
clientSocket = new Socket(AddressF amily.InterNetw ork, SocketType.Stre am,
ProtocolType.Tc p);
clientSocket.Se tSocketOption(S ocketOptionLeve l.Socket,
SocketOptionNam e.SendBuffer, blockSize);
clientSocket.Co nnect(ep);
byte [] info;
byte [] initBuf = new byte[8];
// Setting the block size into first 4 bytes.
info = BitConverter.Ge tBytes(blockSiz e);
int i = 0;
for( ; i<info.Length; ++i )
{
initBuf[i] = info[i];
}
// Setting the overall data size into bytes 4 to 7.
info = BitConverter.Ge tBytes(rowData. Length);
for( i=0; i<info.Length; ++i )
{
initBuf[4+i] = info[i];
}
clientSocket.Se nd( initBuf );
// Sending the data in a 65535 block size.
int length, sentSize;
for( i=0; i < blockCount ; ++i )
{
if( i < (blockCount - 1) )
{
length = blockSize;
}
else
{
length = rowData.Length - (i * blockSize);
}
sentSize = clientSocket.Se nd(rowData, i*blockSize, length,
System.Net.Sock ets.SocketFlags .None);
}
clientSocket.Cl ose();
//////////////////////////////////////////////////////////////////////////
/// The TCP Server
//////////////////////////////////////////////////////////////////////////
IPEndPoint ipNport = new IPEndPoint(IPAd dress.Parse("Se rver IP"), 31001)
TcpListener m_server = new TcpListener(ipN port);
ArrayList m_socketListene rsList = new ArrayList();
// Start the Server and start the thread to listen to client requests.
m_server.Start( );
m_serverThread = new Thread( new ThreadStart(Ser verThreadStart) );
m_serverThread. Start();
private void ServerThreadSta rt()
{
// Client Socket variable;
Socket clientSocket = null;
TCPSocketListen er socketListener = null;
while( true )
{
// Wait for any client requests and if there is any
// request from any client accept it (Wait indefinitely).
clientSocket = m_server.Accept Socket();
socketListener = new TCPSocketListen er(clientSocket );
// Add the socket listener to an array list in a thread safe fashion.
lock( m_socketListene rsList )
{
m_socketListene rsList.Add(clie ntSocket);
}
// Start a communicating with the client in a different thread.
socketListener. StartSocketList ener();
}
}
public class TCPSocketListen er
{
private int m_ID;
private int m_DataSize = 0;
private int m_TotalByteRcvd = 0;
private bool m_IsfirstBlock = true;
private Socket m_clientSocket = null;
public TCPSocketListen er(Socket clientSocket)
{
m_clientSocket = clientSocket;
}
public void StartSocketList ener()
{
m_clientListene rThread = new Thread(new
ThreadStart(Soc ketListenerThre adStart));
m_clientListene rThread.Start() ;
}
private void SocketListenerT hreadStart()
{
int size = 0;
byte [] byteBuffer = new byte[131072];// 128 Kilobyte.
while( true )
{
size = m_clientSocket. Receive(byteBuf fer);
if( size > 0 )
{
if( m_IsfirstBlock )
{
m_TotalByteRcvd = 0;
blocksSize = BitConverter.To Int32(rowdata, 4);
m_DataSize = BitConverter.To Int32(rowdata, 8);
m_Buffer = new byte[dataSize];
m_clientSocket. SetSocketOption (SocketOptionLe vel.Socket,
SocketOptionNam e.ReceiveBuffer , blocksSize);
}
else
{
m_TotalByteRcvd += size;
if( m_TotalByteRcvd >= m_DataSize )
{
break;
}
}
}
}
m_clientSocket. Close();
}
}
/////////////////////////////////////////////////////////////
I hope it's clear enough.
Any Idea will highly appreciated.
---------------------
Thanks & Regards
Sharon
I assume you have tried debugging both client and server in problem
situations. Did you notice anything different? I find it very strange
that when you replace the computer roles (client/server), the program
stops working.
For me just by looking at the code is really hard to say what could be
wrong. I took a look and nothing seemed out of order there anyways.
First off, it would be helpful if you could post a complete sample (one that
anyone can compile and run without modifications). But anyway, comments
inline:
"Sharon" <Sh****@discuss ions.microsoft. com> wrote in message
news:ED******** *************** ***********@mic rosoft.com... Ok, here is the code. I hope I didn't make any mistakes coping and cleaning the code when posting it:
////////////////////////////////////////////////////////////////////////// /// The TCP Client ////////////////////////////////////////////////////////////////////////// int blockSize = 65535; byte [] rowData = new byte[1048576];// 1 MByte int blockCount = rowData.Length/blockSize + ((rowData.Lengt h % blockSize == 0) ? 0 : 1); IPEndPoint ep = new IPEndPoint(IPAd dress.Parse("Se rver IP"), 31001); clientSocket = new Socket(AddressF amily.InterNetw ork, SocketType.Stre am, ProtocolType.Tc p); clientSocket.Se tSocketOption(S ocketOptionLeve l.Socket, SocketOptionNam e.SendBuffer, blockSize); clientSocket.Co nnect(ep); byte [] info; byte [] initBuf = new byte[8]; // Setting the block size into first 4 bytes. info = BitConverter.Ge tBytes(blockSiz e); int i = 0; for( ; i<info.Length; ++i ) { initBuf[i] = info[i]; } // Setting the overall data size into bytes 4 to 7. info = BitConverter.Ge tBytes(rowData. Length); for( i=0; i<info.Length; ++i ) { initBuf[4+i] = info[i]; } clientSocket.Se nd( initBuf );
// Sending the data in a 65535 block size. int length, sentSize; for( i=0; i < blockCount ; ++i ) { if( i < (blockCount - 1) ) { length = blockSize; } else { length = rowData.Length - (i * blockSize); } sentSize = clientSocket.Se nd(rowData, i*blockSize, length, System.Net.Sock ets.SocketFlags .None); } clientSocket.Cl ose();
////////////////////////////////////////////////////////////////////////// /// The TCP Server ////////////////////////////////////////////////////////////////////////// IPEndPoint ipNport = new IPEndPoint(IPAd dress.Parse("Se rver IP"), 31001) TcpListener m_server = new TcpListener(ipN port); ArrayList m_socketListene rsList = new ArrayList(); // Start the Server and start the thread to listen to client requests. m_server.Start( ); m_serverThread = new Thread( new ThreadStart(Ser verThreadStart) ); m_serverThread. Start();
private void ServerThreadSta rt() { // Client Socket variable; Socket clientSocket = null; TCPSocketListen er socketListener = null; while( true ) { // Wait for any client requests and if there is any // request from any client accept it (Wait indefinitely). clientSocket = m_server.Accept Socket(); socketListener = new TCPSocketListen er(clientSocket ); // Add the socket listener to an array list in a thread safe fashion. lock( m_socketListene rsList ) { m_socketListene rsList.Add(clie ntSocket); } // Start a communicating with the client in a different thread. socketListener. StartSocketList ener(); } }
public class TCPSocketListen er { private int m_ID; private int m_DataSize = 0; private int m_TotalByteRcvd = 0; private bool m_IsfirstBlock = true; private Socket m_clientSocket = null;
public TCPSocketListen er(Socket clientSocket) { m_clientSocket = clientSocket; } public void StartSocketList ener() { m_clientListene rThread = new Thread(new ThreadStart(Soc ketListenerThre adStart)); m_clientListene rThread.Start() ; } private void SocketListenerT hreadStart() { int size = 0; byte [] byteBuffer = new byte[131072];// 128 Kilobyte.
while( true ) { size = m_clientSocket. Receive(byteBuf fer); if( size > 0 ) {
At this point, it appears you assume you have received exactly 8 bytes but
that is not necessarily the case. 'size' could be anything from 1 to number
of bytes in the TCP receive buffer. Most notably, if the number of bytes is
greater than 8, then you're missing out the extra bytes here as the next
iteration won't pick them up.
if( m_IsfirstBlock ) { m_TotalByteRcvd = 0; blocksSize = BitConverter.To Int32(rowdata, 4); m_DataSize = BitConverter.To Int32(rowdata, 8); m_Buffer = new byte[dataSize]; m_clientSocket. SetSocketOption (SocketOptionLe vel.Socket, SocketOptionNam e.ReceiveBuffer , blocksSize); } else { m_TotalByteRcvd += size; if( m_TotalByteRcvd >= m_DataSize ) { break; } } } } m_clientSocket. Close(); } } /////////////////////////////////////////////////////////////
So the lesson is that never assume anything about the amount of data you
receive with TCP. If the sender calls Send two times trying to send e.g.,
16-bytes each time, the receiver might receive all of it in one 16-byte
chunk, or in two 8-byte chunks, or... It is the receiver's responsibility to
handle all possible cases correctly.
HTH,
Sami
Hi Sami,
Thanks a lot for your answer, your observation is the problem.
The client is sending 8 byte buffer in the first block, therefore I assumed
at the server side that this is the first buffer size I should receive, BUT
there are cases when this first block is 73008 bytes and not 8 bytes, causing
me to lose 73000 bytes.
So now, after I fixed it, it works fine even if I run 20 fast clients and a
server PC that is also running Outlook and Internet Radio.
So now it all good.
Again, thanks a lot.
Sharon This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Qiangning Hong |
last post by:
A class Collector, it spawns several threads to read from serial port.
Collector.get_data() will get all the data they have read since last
call. Who can tell me whether my implementation correct?
class Collector(object):
def __init__(self):
self.data =
spawn_work_bees(callback=self.on_received)
def on_received(self, a_piece_of_data):
|
by: HB Kim |
last post by:
Hello,
What could possibly cause data in the SQL server database to be
removed, except being deleted manually? We had a couple of situations
where data in certain records disappeared although the records were
still there. The data is entered and editted through the web interface
in ASP. The web interface is accessed by anyone who has an account in
our database.
I am more of a web programmer, not a SQL server administrator, so not
very...
|
by: sid |
last post by:
Data loss in Access-97 from VB 6.0
I have encountered Random data loss in our access database.
Sometimes the users call in saying that the records entered by them
are lost. The users, use our VB front end to enter the data (Users do
not enter data directly into the database)
Most of the times I have noticed that the problem occurs when users
add new records.
All our tables have a unique alpha-numeric primary key.
|
by: Neil Ginsberg |
last post by:
I'm having some problems with an Access 2000 MDB file with a SQL Server 7
back end, using ODBC linked tables. I previously wrote about this, but am
reposting it with some additional information and in summary form, in hopes
that someone might have an idea about what's going on.
I am using a bound form which is losing data a significant portion of the
time. Basically, the form contains 6 fields and three subforms, as follows:
Field A...
|
by: Saket Mundra |
last post by:
I have a web application with two forms. After user enters data in first form
he is directed to the second form. After Filling the second form as he clicks
on save button, the data entered is stored in the database using a
Transaction Object, That inserts data, entered by user in both the forms, in
the database.
My problem is where shall i store the data entered by the user in the first
form when he is redirected to next form and till i...
| |
by: byeung |
last post by:
Hi,
I am trying to check if a particular record already exists in an Access
database through Excel vba code. Through code obtained at another
forum, I got the following:
***********************************************************************
Sub TheButton()
|
by: Charlie of Bolton |
last post by:
Hi,
I have to below script,
and everything seems to work except
that if I entered the Primary IP and Secondaries IP, with such
number; 10.100.1.11 or 10.10.10.245 the last numbers of my IP are missing
in my logs file (c:/tmp/myprimarylogs.xls) Here is the result, you see, '10.100.1.1 should be 10.100.1.11
and 10.10.10.2 should be 10.10.10.224 how can I resolve this issue ?
and I need to know How to add the time : time.asctime()...
|
by: elliot.li.tech |
last post by:
Hello everyone,
I'm migrating a C++ program from 32-bit systems to 64-bit systems. The
old programmers used some annoying assignments like assigning "long"
to "int", which may lead to data loss.
Is it possible to let the compiler (specifically, GCC) spew some
warnings on this kind of implicit type casts?
Or you suggest use some other static source codes analysis tools?
|
by: Haas C |
last post by:
Hi all,
I have a table with two columns, labeled Year and Loss. In the Year
field, I have the numbers 1 to 10,000, each which can or cannot
repeat. In the Loss column, i have numbers corresponding to the
Years...for example:
Year, Loss
1, 568
1, 621
|
by: Debadatta Mishra |
last post by:
Introduction
In this article I will provide you an approach to manipulate an image file. This article gives you an insight into some tricks in java so that you can conceal sensitive information inside an image, hide your complete image as text ,search for a particular image inside a directory, minimize the size of the image. However this is not a new concept, there is a concept called Steganography which enables to conceal your secret...
|
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...
| |
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,...
|
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...
|
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,...
|
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...
|
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...
|
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...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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...
| |