473,396 Members | 1,891 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,396 software developers and data experts.

C# socket reconnect

Hi. I am having a problem on handling asynchronous sockets in C#. I
implemented a pair of client and server sockets. The connection is ok when
first connected. However, when I turned off the server socket, the client
is able to connect, but cannot send anything out. It seems that the
Socket.Connected is false but I received no disconnection event. Any idea
on how to solve the problem?

Thanks.
using System;
using System.Collections.Generic;
using System.Text;

using System.Net.Sockets;
using System.Threading;

using System.Collections;

namespace socket
{
public sealed class SocketClient
{

Queue qsend = null;
//default setting
private const int DEFAULT_PORT = 1024;
private const string DEFAULT_IP = "127.0.0.1";
private const int SOCKET_BUFFER_SIZE = 256;

public delegate void ErrorEvent(object sender, string err);
public event ErrorEvent OnErrorEvent;

public delegate void ConnectEvent(object sender);
public event ConnectEvent OnConnectEvent;

public delegate void DisconnectEvent(object sender);
public event DisconnectEvent OnDisconnectEvent;

public delegate void ReceiveEvent(object sender, byte[] buffer, int
len);
public event ReceiveEvent OnReceiveEvent;

private static ManualResetEvent sendDone = new
ManualResetEvent(false);

private Socket handle = null;

private int bytesSent = 0;

private string ip;

private int port;

public bool Connected
{
get
{
return Handle.Connected;
}
}

//socket handle
public Socket Handle
{
get
{
return handle;
}
set
{
handle = value;
}
}
/// <summary>
/// Constructor
/// </summary>
public SocketClient()
{

try
{
qsend = new Queue();

handle = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);

ip = DEFAULT_IP;
port = DEFAULT_PORT;
}
catch (SocketException e)
{
ThrowError(e.Message);
}
}
public SocketClient(Socket workerSocket)
{
try
{
qsend = new Queue();

handle = workerSocket;

ip = DEFAULT_IP;
port = DEFAULT_PORT;
}
catch (SocketException e)
{
ThrowError(e.Message);
}
}
public void Connect(string ip, int port)
{
this.ip = ip;
this.port = port;
try
{
//Console.WriteLine(this, "Begin Connect");
handle.BeginConnect(ip, port, new
AsyncCallback(OnConnectCallBack), null);
}
catch (SocketException e)
{
ThrowError(e.Message);
}
catch (Exception e)
{
ThrowError(e.Message);
}
}
private void OnConnectCallBack(IAsyncResult asyn)
{
try
{
//Console.WriteLine(this, "End Connect");
handle.EndConnect(asyn);

if (OnConnectEvent != null)
{
OnConnectEvent(this);
}
else
{
Console.WriteLine(this, "OnConnectEvent = null");
}
}
catch (SocketException e)
{
ThrowError(e.Message);
}
catch (Exception e)
{
ThrowError(e.Message);
}
}
public void Disconnect()
{
try
{
handle.BeginDisconnect(true, new
AsyncCallback(OnDisconnectCallBack), null);
}
catch (SocketException e)
{
ThrowError(e.Message);
}
catch (Exception e)
{
ThrowError(e.Message);
}
}
private void CloseSocket()
{
try
{
Console.WriteLine(this, "CloseSocket");
handle.Shutdown(SocketShutdown.Both);
handle.Close();

//if (OnDisconnectEvent != null)
//{
// OnDisconnectEvent(this);
//}
}
catch (SocketException e)
{
ThrowError(e.Message);
//throw e;
}
catch (Exception e)
{
ThrowError(e.Message);
//throw e;
}
finally
{
if (OnDisconnectEvent != null)
{
OnDisconnectEvent(this);
}
}
}
private void OnDisconnectCallBack(IAsyncResult asyn)
{
try
{
handle.EndDisconnect(asyn);

CloseSocket();
}
catch (SocketException e)
{
ThrowError(e.Message);
}
catch (Exception e)
{
ThrowError(e.Message);
}
}

public void Send(byte[] buffer, int len)
{
lock (qsend)
{
try
{
//int bytesSent = 0;
bytesSent = 0;
int bytesRemain = len - bytesSent;

while (bytesSent < buffer.Length)
{
bytesRemain = len - bytesSent;

byte[] sendBuffer = new byte[bytesRemain];

Array.Copy(buffer, bytesSent, sendBuffer, 0,
bytesRemain);

try
{
bytesSent += AsyncSend(sendBuffer, bytesRemain);

if (bytesSent != len)
{
int j = 0;
}
}
catch (SocketException e)
{
ThrowError(e.Message);
//throw e;
}
catch (Exception e)
{
ThrowError(e.Message);
//throw e;
}
}
}
catch (Exception e)
{
ThrowError(e.Message);
//throw e;
}
}
}

private void OnSendCallBack1(IAsyncResult asyn)
{

//int bytesSent = (int)asyn.AsyncState;

SocketError err = new SocketError();

bytesSent = handle.EndSend(asyn, out err);
}
public int AsyncSend(byte[] buffer, int len)
{
try
{
sendDone.Reset();

bytesSent = 0;

handle.BeginSend(
buffer,
0,
len,
SocketFlags.None,
new AsyncCallback(OnSendCallBack),
null);

sendDone.WaitOne();

return bytesSent;
}
catch (SocketException e)
{
ThrowError(e.Message);
return -1;
throw e;
}
catch (Exception e)
{
ThrowError(e.Message);
return -1;
throw e;
}
}
private void OnSendCallBack(IAsyncResult asyn)
{
try
{
//int bytesSent = (int)asyn.AsyncState;

SocketError err = new SocketError();

bytesSent = handle.EndSend(asyn, out err);
}
catch (SocketException e)
{
ThrowError(e.Message);
//throw e;
}
catch (Exception e)
{
ThrowError(e.Message);
//throw e;
}
finally
{
sendDone.Set();
}
}
public void Receive()
{
try
{
if (Connected)
{
byte[] buffer = new byte[SOCKET_BUFFER_SIZE];
handle.BeginReceive(buffer, 0, SOCKET_BUFFER_SIZE,
SocketFlags.None, new AsyncCallback(OnReceiveCallBack), buffer);
}
}
catch (SocketException e)
{
//error code for disconnect socket
if (e.ErrorCode == 10054)
{
CloseSocket();
}
else
{
ThrowError(e.Message);
throw e;
}
}
catch (Exception e)
{
ThrowError(e.Message);
//throw e;
}
}
private void OnReceiveCallBack(IAsyncResult asyn)
{
try
{
SocketError err = new SocketError();

int bytesRead = handle.EndReceive(asyn, out err);

if (err.ToString() != "Success")
{
Console.WriteLine(this, "OnReceiveCallBack:" +
err.ToString());
}

if (bytesRead <= 0)
{
Console.WriteLine(this, "bytesRead = 0");
CloseSocket();
}
else if (bytesRead 0)
{
//Console.WriteLine(this, "bytesRead =" + bytesRead);
byte[] buffer = new byte[bytesRead];

Array.Copy((byte[])asyn.AsyncState, 0, buffer, 0,
bytesRead);

if (OnReceiveEvent != null)
{
OnReceiveEvent(this, buffer, bytesRead);
}

Receive();
}
}
catch (SocketException e)
{
//error code for disconnect socket
if (e.ErrorCode == 10054)
{
CloseSocket();
}
else
{
ThrowError(e.Message);
throw e;
}
}
catch (Exception e)
{
ThrowError(e.Message);
//throw e;
}
}
private void ThrowError(string err)
{
Console.WriteLine(this, err);
if (OnErrorEvent != null)
{
OnErrorEvent(this, err);
}
}
public void BeginReceiveCallback()
{
Receive();
}
}
}

Jun 13 '07 #1
3 14342
On Wed, 13 Jun 2007 03:06:43 -0700, Cheryl <ju*********@excite.comwrote:
Hi. I am having a problem on handling asynchronous sockets in C#. I
implemented a pair of client and server sockets. The connection is ok
when first connected. However, when I turned off the server socket, the
client is able to connect, but cannot send anything out. It seems that
the Socket.Connected is false but I received no disconnection event.
Any idea on how to solve the problem?
Can you clarify your question? What do you mean by "turned off the server
socket"? Did you actually close the socket? If so, I don't understand
why the "client is able to connect". I would expect some error to be
thrown in the call to EndConnect() (like WSAEHOSTUNREACH). You don't seem
to have any code that does anything other than display the error in this
case, so it seems possible to me that you do in fact display the error but
then haven't done any cleanup to remove the client socket that failed to
connect.

Also, a quick glance through your code shows that you are not copying the
event handler instances before executing them. This leads to the
possibility that between the time when you check for null and the time you
actually try to execute the handlers, it could become null and cause a
null reference exception.

Pete
Jun 13 '07 #2
thx. What I meant was to turn off the server socket and turned that on
again. Do you mean that I have to once again copy the socket.connect status
in the constructor?

"Peter Duniho" <Np*********@nnowslpianmk.com在郵件
news:op***************@petes-computer.local ä¸*撰寫...
On Wed, 13 Jun 2007 03:06:43 -0700, Cheryl <ju*********@excite.comwrote:
>Hi. I am having a problem on handling asynchronous sockets in C#. I
implemented a pair of client and server sockets. The connection is ok
when first connected. However, when I turned off the server socket, the
client is able to connect, but cannot send anything out. It seems that
the Socket.Connected is false but I received no disconnection event.
Any idea on how to solve the problem?

Can you clarify your question? What do you mean by "turned off the server
socket"? Did you actually close the socket? If so, I don't understand
why the "client is able to connect". I would expect some error to be
thrown in the call to EndConnect() (like WSAEHOSTUNREACH). You don't seem
to have any code that does anything other than display the error in this
case, so it seems possible to me that you do in fact display the error but
then haven't done any cleanup to remove the client socket that failed to
connect.

Also, a quick glance through your code shows that you are not copying the
event handler instances before executing them. This leads to the
possibility that between the time when you check for null and the time you
actually try to execute the handlers, it could become null and cause a
null reference exception.

Pete
Jun 14 '07 #3
problem solved. it's actually a problem on initializing the socket again.
thx
"Cheryl" <ju*********@excite.com在郵件
news:ey**************@TK2MSFTNGP02.phx.gbl ä¸*撰寫...
thx. What I meant was to turn off the server socket and turned that on
again. Do you mean that I have to once again copy the socket.connect
status
in the constructor?

"Peter Duniho" <Np*********@nnowslpianmk.com在郵件
news:op***************@petes-computer.local ä¸*撰寫...
>On Wed, 13 Jun 2007 03:06:43 -0700, Cheryl <ju*********@excite.com>
wrote:
>>Hi. I am having a problem on handling asynchronous sockets in C#. I
implemented a pair of client and server sockets. The connection is ok
when first connected. However, when I turned off the server socket, the
client is able to connect, but cannot send anything out. It seems that
the Socket.Connected is false but I received no disconnection event. Any
idea on how to solve the problem?

Can you clarify your question? What do you mean by "turned off the
server socket"? Did you actually close the socket? If so, I don't
understand why the "client is able to connect". I would expect some
error to be thrown in the call to EndConnect() (like WSAEHOSTUNREACH).
You don't seem to have any code that does anything other than display the
error in this case, so it seems possible to me that you do in fact
display the error but then haven't done any cleanup to remove the client
socket that failed to connect.

Also, a quick glance through your code shows that you are not copying the
event handler instances before executing them. This leads to the
possibility that between the time when you check for null and the time
you actually try to execute the handlers, it could become null and cause
a null reference exception.

Pete
Jun 14 '07 #4

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

Similar topics

3
by: Thomas Hervé | last post by:
My problem is not really python specific but as I do my implementation in python I hope someone here can help me. I have two programs that talk through a socket. Here is the code : <server>...
8
by: Wally | last post by:
Hallo Is there anybody able to tell me if and how to restore a lost socket communication? I try to explain. Computer A and computer B are net connected and they estabilished a socket connection....
6
by: Sharon | last post by:
Hi all. I'm trying first time async socket connection. In all the examples i've seen, the server connection is closed when the message is complete. Is it common to close the connection after...
5
by: DaTurk | last post by:
I have this application that has one sender, and multiple receivers, the receivers are subscribing to a multicast group to which the sender is sending information synchronously, while the receivers...
18
by: nephish | last post by:
lo there, i have a simple app that connects to a socket to get info from a server i looks like this serverhost = 'xxx.xxx.xxx.xxx' serverport = 9520 aeris_sockobj =...
1
by: Jay | last post by:
I have a client app sending messages over the socket on a certain port. In the client app: I do this for every message I need to send: 1. Create a socket and connect. 2. Send message 3. Close...
0
by: Kursat | last post by:
Hi, I developed a socket client application which connects to a server application and axchange some data. I test Connected property of the socket object and try to reconnect if its value is...
2
by: dougmcmurtry | last post by:
I have an Asynchronous socket that sends data to a server for credit card approvals. The socket is kept alive by the server through a heartbeat that sends a "beat" every 90 seconds. Trouble is that...
3
by: Jason Kristoff | last post by:
I'm trying to make something that once it is disconnected will automatically try to reconnect. I'll add some more features in later so it doesn't hammer the server but right now I just want to...
0
by: Dreea | last post by:
Hello everybody I am working on a client application that connects to a C# server using the Socket class. I am trying to handle the case in which the server goes offline, and I would like the...
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: 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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...
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
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...

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.