473,373 Members | 1,010 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,373 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 4117
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: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...

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.