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

Not understanding Sockets Probably Simple

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
1 1748
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Johannes Eble | last post by:
Hello Python community, I am trying the echo-client and echo-server examples in Chapter 10, "Programming Python" by Mark Lutz. It is probably the most simple sockets sample: A socket server just...
2
by: Tero Saarni | last post by:
Hi, I have several threads communicating with each other using events stored in Queues. Threads block on Queue.get() until somebody publishes an event in thread's event queue. I need to add...
4
by: Julia Goolia | last post by:
hello, i read that it is bad to use threads with tkinter. so my question is how does one create a gui program with sockets? at one point you have to call mainloop() which does not return. ...
11
by: Nick Keighley | last post by:
I'm probably missing something rather obvious, but is there a known problem with getting a Python based socket program to communicate with a C based socket program? A simple echo server written in...
4
by: Garam | last post by:
I need to write a substantial amount of network code in C. The thing is, it has to be able to run on both Unix and Windows. Rather than writing separate code for each, I was looking for something...
7
by: Bill English | last post by:
How do I send an object from one computer to another? -- I am a 14 year old C# developer, I am completely self taught, so please don't get mad if I ask a stupid question. Thanks.
4
by: Abubakar | last post by:
Hi, I am writing a server in C# and client in C++ (pure, not managed). The communication goes on through sockets. In C# I am using NetworkStream to send text data (by converting it to byte array)...
5
by: Dan Ritchie | last post by:
I've got a client/server app that I used to send large amounts of data via UDP to the client. We use it in various scenarios, one of which includes rendering a media file on the client as it is...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
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
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.