By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,649 Members | 2,142 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,649 IT Pros & Developers. It's quick & easy.

Not understanding Sockets Probably Simple

P: n/a
jm
Easy probably, please read on. I know some of you have commented
already about some of my socket question. I appreciate that.

I have a Form1:

static void Main()
{
Application.Run(new Form1());
clsListening.AsynchronousSocketListener.StartListe ning();

}

In the clsListening below is the code. It is all straight from MSDN.
The problem is this:

If I run this the Form will load, but the the next line will not
execute until the form Form1 is closed (I just hit the X.) I know
this is true because netstat -a | find "8002" reveals it is not
listenting. Close the form and voila it is listening.

I do not understand why it is doing this. Please help me understand
this behavior. BTW, the listener and all works, I have to have the
form running because I need an icon in the system tray.

Also, if I reverse the two the Form1 will never run, because of the
While(true) for the listener (at least I think that is why.)

I just want the listener to run and the form to run:

I thought I would try this, but it failed with the same results,
except the Form1 never ran:

static void Main()
{
Application.Run(new Form1());
}

private void Form1_Load(object sender, System.EventArgs e)
{
clsListening.AsynchronousSocketListener.StartListe ning();
}

The slight difference here was that the icon was in the system tray,
but the form was not visible! Thank you for any help here.

From MSDN, sorry for long post, not even sure it is entirely relevant
for this basic question:

public class clsListening
{
public clsListening()
{
//
// TODO: Add constructor logic here
//
}
// State object for reading client data asynchronously
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousSocketListener
{

// Incoming data from client.
public static string data = null;

// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);

public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];

// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8002);

// Create a TCP/IP socket.
Socket listener = new
Socket(AddressFamily.InterNetwork,SocketType.Strea m, ProtocolType.Tcp
);

// Bind the socket to the local endpoint and listen for incoming
connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(100);

while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();

// Start an asynchronous socket to listen for connections.
//MessageBox.Show("Waiting for a connection...");

listener.BeginAccept( new
AsyncCallback(AcceptCallback),listener );
// Wait until a connection is made before continuing.

allDone.WaitOne();
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}

public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();

// Get the socket that handles the client request.
Socket listener = (Socket) ar.AsyncState;
Socket handler = listener.EndAccept(ar);

// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new
AsyncCallback(ReadCallback), state);
}

public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;

// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket handler = state.workSocket;

// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);

if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buf fer,0,bytesRead));

// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
// All the data has been read from the
// client. Display it on the console.
MessageBox.Show("Alert Update Received Read {0} bytes from socket. \n
Data : {1}" + content.Length.ToString() + content.ToString() );

UpdateIcons ui = new UpdateIcons();
ui.Recieved(content.ToString()); //I added this
// Echo the data back to the client.
Send(handler, content);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new
AsyncCallback(ReadCallback), state);
}
}
}

private static void Send(Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);

// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0, new
AsyncCallback(SendCallback), handler);

}

private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket) ar.AsyncState;

// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
MessageBox.Show("Alert Update Receipt Sent {0} bytes to client.",
bytesSent.ToString());

handler.Shutdown(SocketShutdown.Both);
handler.Close();

}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
}
}
Nov 16 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
jm wrote:
Easy probably, please read on. I know some of you have commented
already about some of my socket question. I appreciate that.

I have a Form1:

static void Main()
{
Application.Run(new Form1());
clsListening.AsynchronousSocketListener.StartListe ning();

}

In the clsListening below is the code. It is all straight from MSDN.
The problem is this:

If I run this the Form will load, but the the next line will not
execute until the form Form1 is closed (I just hit the X.) I know
this is true because netstat -a | find "8002" reveals it is not
listenting. Close the form and voila it is listening.

I do not understand why it is doing this. Please help me understand
this behavior. BTW, the listener and all works, I have to have the
form running because I need an icon in the system tray.

Also, if I reverse the two the Form1 will never run, because of the
While(true) for the listener (at least I think that is why.)

I just want the listener to run and the form to run:

I thought I would try this, but it failed with the same results,
except the Form1 never ran:

static void Main()
{
Application.Run(new Form1());
}

private void Form1_Load(object sender, System.EventArgs e)
{
clsListening.AsynchronousSocketListener.StartListe ning();
}

The slight difference here was that the icon was in the system tray,
but the form was not visible! Thank you for any help here.

From MSDN, sorry for long post, not even sure it is entirely relevant
for this basic question:

public class clsListening
{
public clsListening()
{
//
// TODO: Add constructor logic here
//
}
// State object for reading client data asynchronously
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousSocketListener
{

// Incoming data from client.
public static string data = null;

// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);

public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];

// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8002);

// Create a TCP/IP socket.
Socket listener = new
Socket(AddressFamily.InterNetwork,SocketType.Strea m, ProtocolType.Tcp
);

// Bind the socket to the local endpoint and listen for incoming
connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(100);

while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();

// Start an asynchronous socket to listen for connections.
//MessageBox.Show("Waiting for a connection...");

listener.BeginAccept( new
AsyncCallback(AcceptCallback),listener );
// Wait until a connection is made before continuing.

allDone.WaitOne();
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}

public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();

// Get the socket that handles the client request.
Socket listener = (Socket) ar.AsyncState;
Socket handler = listener.EndAccept(ar);

// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new
AsyncCallback(ReadCallback), state);
}

public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;

// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket handler = state.workSocket;

// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);

if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buf fer,0,bytesRead));

// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
// All the data has been read from the
// client. Display it on the console.
MessageBox.Show("Alert Update Received Read {0} bytes from socket. \n
Data : {1}" + content.Length.ToString() + content.ToString() );

UpdateIcons ui = new UpdateIcons();
ui.Recieved(content.ToString()); //I added this
// Echo the data back to the client.
Send(handler, content);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new
AsyncCallback(ReadCallback), state);
}
}
}

private static void Send(Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);

// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0, new
AsyncCallback(SendCallback), handler);

}

private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket) ar.AsyncState;

// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
MessageBox.Show("Alert Update Receipt Sent {0} bytes to client.",
bytesSent.ToString());

handler.Shutdown(SocketShutdown.Both);
handler.Close();

}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
}
}

Well, Application.Run(...) is a modal function, so program waits for it
to finish until next line will be executed.

Now, why don't you want to run the server withing your form class?
Also Form1_Load has to be linked to the form events.
I have server starting in Load event and it works fine.

Andrey


Nov 16 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.