I've got a simple problem I guess. How do I know when a connection is
terminated without losing any data?
I do something like the code below, but sometimes between
socket.Receive and socket.Send I get the last chunk of data and am not
able to retrieve it anymore cause the socket will be dead.
Loop:
{
socket.Receive
<----------- data arrives
socket.Send(tes tData)
<----------- exception, socket closed, out of loop (can't receive
anymore because it throws an exception)
(shall I put a thread delay here to assure that the Receive method
receives the last chunk)
}
Here is the relevant code:
*************** *************** *********
while(true)
{
try
{
int
j=socket.Receiv e(bytes,receive dOffset,socket. Available,Socke tFlags.None);
receivedOffset+ =j;
}
catch(Exception )
{
}
//Check if the connection is closed
//and there is no more data to get
try
{
byte[] buffer=Encoding .UTF8.GetBytes( "\r\n");
socket.Send(buf fer);
}
catch(Exception )
{
//MessageBox.Show (socket.Connect ed.ToString());
break;
}
} 2 4155
I believe that you have to call the socket.Connect method on your socket
before sending the data with both a connection-oriented and connectionless
protocol. When you call connect you have to send it a variable of type
IPEndPoint according to the Microsoft Online Documentation. Here is the
sample code they send with MSVS2003
[C#]
IPHostEntry lipa = Dns.Resolve("ho st.contoso.com" );
IPEndPoint lep = new IPEndPoint(lipa .AddressList[0], 11000);
Socket s = new Socket(lep.Addr ess.AddressFami ly,
SocketType.Stre am,
ProtocolType.Tc p);
try{
s.Connect(lep);
}
catch (Exception e){
Console.WriteLi ne("Exception Thrown: " + e.ToString());
}
byte[] msg = Encoding.ASCII. GetBytes("This is a test");
// Blocks until send returns.
int i = s.Send(msg);
// Blocks until read returns.
byte[] bytes = new byte[1024];
s.Receive(bytes );
//Displays to the screen.
Console.WriteLi ne(Encoding.ASC II.GetString(by tes));
s.Shutdown(Sock etShutdown.Both );
s.Close();
hope this helps,
Chris
--
Securing your systems is much like fighting off disease -- as long as you
maintain basic hygiene, you're likely to be okay, but you'll never be
invulnerable.
Steve Shah - Unix Systems Network Administrator
"Nuno Magalhaes" <nu************ @hotmail.com> wrote in message
news:11******** ************@g4 3g2000cwa.googl egroups.com... I've got a simple problem I guess. How do I know when a connection is terminated without losing any data?
I do something like the code below, but sometimes between socket.Receive and socket.Send I get the last chunk of data and am not able to retrieve it anymore cause the socket will be dead. Loop: { socket.Receive <----------- data arrives socket.Send(tes tData) <----------- exception, socket closed, out of loop (can't receive anymore because it throws an exception) (shall I put a thread delay here to assure that the Receive method receives the last chunk) }
Here is the relevant code: *************** *************** ********* while(true) { try { int j=socket.Receiv e(bytes,receive dOffset,socket. Available,Socke tFlags.None); receivedOffset+ =j; } catch(Exception ) { } //Check if the connection is closed //and there is no more data to get try { byte[] buffer=Encoding .UTF8.GetBytes( "\r\n"); socket.Send(buf fer); } catch(Exception ) { //MessageBox.Show (socket.Connect ed.ToString()); break; } }
That didn't help. My socket receive and send functions don't block and
what I asked was if there is a method to check if the connection is
active. Socket.Connecti on is not a method, but a property and is
updated only with the last Socket.Send operation that throws an
exception if the connection was closed. What I asked was a solution for
the synchronization of my code because I was losing the last chunk
sometimes.
while(true)
{
try
{
Socket.Receive
Socket.Send
}
catch(Exception )
{
break;
}
}
If the data arrives between socket.Receive and socket.Send I can't get
the last piece of data.
Thanks for your reply, anyway. That was I asked.
Nuno Magalhaes.
P.S.: It will always give an exception because the server will close
the connection at the end of the data transmission.
Chris Springer wrote: I believe that you have to call the socket.Connect method on your socket before sending the data with both a connection-oriented and connectionless protocol. When you call connect you have to send it a variable of type IPEndPoint according to the Microsoft Online Documentation. Here is the sample code they send with MSVS2003
[C#] IPHostEntry lipa = Dns.Resolve("ho st.contoso.com" ); IPEndPoint lep = new IPEndPoint(lipa .AddressList[0], 11000);
Socket s = new Socket(lep.Addr ess.AddressFami ly, SocketType.Stre am, ProtocolType.Tc p); try{ s.Connect(lep); } catch (Exception e){ Console.WriteLi ne("Exception Thrown: " + e.ToString()); }
byte[] msg = Encoding.ASCII. GetBytes("This is a test");
// Blocks until send returns. int i = s.Send(msg);
// Blocks until read returns. byte[] bytes = new byte[1024]; s.Receive(bytes );
//Displays to the screen. Console.WriteLi ne(Encoding.ASC II.GetString(by tes)); s.Shutdown(Sock etShutdown.Both ); s.Close();
hope this helps,
Chris
-- Securing your systems is much like fighting off disease -- as long as you maintain basic hygiene, you're likely to be okay, but you'll never be invulnerable.
Steve Shah - Unix Systems Network Administrator "Nuno Magalhaes" <nu************ @hotmail.com> wrote in message news:11******** ************@g4 3g2000cwa.googl egroups.com... I've got a simple problem I guess. How do I know when a connection is terminated without losing any data?
I do something like the code below, but sometimes between socket.Receive and socket.Send I get the last chunk of data and am not able to retrieve it anymore cause the socket will be dead. Loop: { socket.Receive <----------- data arrives socket.Send(tes tData) <----------- exception, socket closed, out of loop (can't receive anymore because it throws an exception) (shall I put a thread delay here to assure that the Receive method receives the last chunk) }
Here is the relevant code: *************** *************** ********* while(true) { try { int j=socket.Receiv e(bytes,receive dOffset,socket. Available,Socke tFlags.None); receivedOffset+ =j; } catch(Exception ) { } //Check if the connection is closed //and there is no more data to get try { byte[] buffer=Encoding .UTF8.GetBytes( "\r\n"); socket.Send(buf fer); } catch(Exception ) { //MessageBox.Show (socket.Connect ed.ToString()); break; } } This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Michael Kennedy [UB] |
last post by:
Hi,
I have a project using the TcpClient and its associated NetworkStream.
Everything works well except for one condition which I haven't found any
information about dealing with:
How do I detected when the socket connection was closed on the
server-side?
That is, if my client connects to the server and everything is initialized
|
by: Markus Pitha |
last post by:
Hello,
I want to try to program a little server.
I already managed it to send a login message to the connected user, but
I wonder how it works to get information about the connection itself?
With this information, I want to close sockets, which are not in use
anymore (because of quitting by the client).
What's the usual way of programming things like that? I mean, which
return value of which command is usually used for things like that?
...
|
by: Wayne M J |
last post by:
After defining socket etc, and opening the connection(ironic) is there any
way of determining that a connection(sic) was infact made.
The only way I can think of, without access to a .Net machine, is to send a
packet, and see how that is handled.
--
Wayne M Jackson
------
WWW: http://www.wjackson.cable.nu
|
by: Stampede |
last post by:
Hi,
I would like to know if there is any way to check if a file is an XML or a
plain text file?
Opening the file with a FileStream and checking the first character for '<'
seems not very clean and in case of performance not very fast either, as I
would have to open the file twice if it is an XML file. I can't use the file
extension as it is not shure, that every XML file will have the .xml
extension within the system I need this feature....
|
by: Jonathan |
last post by:
Hi,
how to detect when an asynchronous socket is closed?
Thanks!
| |
by: Abubakar |
last post by:
Hi,
lets say I have a connected SOCKET s. At some point in time, I want to know
if the "s" is still valid, that it is still connected. Is there any API that
I can give me this information?
And can I register some callback like thing, that would inform me when "s"
disconnection happens? What I usually do is while I call "send" or "recv", I
get the socket_error and through that I know whats the status. But in this
situation actually I...
|
by: Dirk Reske |
last post by:
Hello,
in msdn stands, that the socket.available property can fire a
SocketException when the remote machine has closed the connection.
why can?
I have to check the number of receivable bytes bevor I receive them, but
when remote closes the connection, it ends in an endless loop...
while(socket.Available < RequiredBytes) {}
|
by: hotting |
last post by:
You must have such headache as I had. But now, aha, I found this
website that really worths our focus: http://www.aotol.com. It is
pretty nice, helping us grasp the latest messages responded to our
requests in the forums and informing us via emails. With it, we dont
need login website again and again to check the latest status our
topics are, coz Aotol does that.
|
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: 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...
|
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: 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: 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
| |