473,398 Members | 2,125 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Checking wether a socket is closed

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(testData)
<----------- 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.Receive(bytes,receivedOffset,socket.Avail able,SocketFlags.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(buffer);
}
catch(Exception)
{
//MessageBox.Show(socket.Connected.ToString());
break;
}
}

Dec 1 '05 #1
2 4124
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("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);

Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(lep);
}
catch (Exception e){
Console.WriteLine("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.WriteLine(Encoding.ASCII.GetString(bytes)) ;
s.Shutdown(SocketShutdown.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********************@g43g2000cwa.googlegrou ps.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(testData)
<----------- 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.Receive(bytes,receivedOffset,socket.Avail able,SocketFlags.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(buffer);
}
catch(Exception)
{
//MessageBox.Show(socket.Connected.ToString());
break;
}
}

Dec 1 '05 #2
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.Connection 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("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);

Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(lep);
}
catch (Exception e){
Console.WriteLine("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.WriteLine(Encoding.ASCII.GetString(bytes)) ;
s.Shutdown(SocketShutdown.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********************@g43g2000cwa.googlegrou ps.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(testData)
<----------- 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.Receive(bytes,receivedOffset,socket.Avail able,SocketFlags.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(buffer);
}
catch(Exception)
{
//MessageBox.Show(socket.Connected.ToString());
break;
}
}


Dec 1 '05 #3

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

Similar topics

6
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...
2
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...
0
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...
2
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...
0
by: Jonathan | last post by:
Hi, how to detect when an asynchronous socket is closed? Thanks!
6
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...
3
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...
2
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...
0
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...
0
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...

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.