473,503 Members | 1,818 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Asynchronous Socket Server Advice

I'm writing a little console socket server but I'm having some
difficulty. Can I ask your advice - where is the best place to get
some help on that topic? It would be nice if some people who knew what
they were doing could take a look at my code and tell me where and why
I'm going wrong.

Any suggestions of groups or forums?
Nov 18 '05 #1
7 2364
I'll just post some code here in case anyone fancies a look:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections;
using System.Diagnostics;
// 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();
// the group this socket belongs to
public int group;
}
public class AsynchronousSocketListener
{
public static int currentGroup = 0;
public static ArrayList connectedClients = new ArrayList();
public static ArrayList connectedClientGroups = new ArrayList();
public static string grp = string.Empty;
// Incoming data from client.
public static string data = null;

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

public AsynchronousSocketListener()
{
}

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

// Establish the local endpoint for the socket.
// That's the computer running the server btw
// 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, 11000);

// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, 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.
Console.WriteLine("Waiting for a connection...");
// (method, object)
listener.BeginAccept(new AsyncCallback(AcceptCallback),
listener);

// Wait until a connection is made before continuing.
allDone.WaitOne();
}

}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

Console.WriteLine("\nPress ENTER to continue...");
Console.Read();

}

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);

// Add this newly connected client socket to our arraylist

// Create the state object - CUSTOM OBJECT!
StateObject state = new StateObject();
state.workSocket = handler;

handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}

// this is basically constantly called
public static void ReadCallback(IAsyncResult ar)
{

Console.WriteLine("ReadCallBack");
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.buffer,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)
{
state.sb.Remove(0,state.sb.Length);
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data
: {1}",
content.Length, content );

// Echo the data back to the connected clients.
// send the group which this client belongs to - that's
the only people that need to see this data
sendToClients(state.group.ToString(), content);
}
// initial string will be the group this client is attached to
// this will be the first to be called.
else if (content.IndexOf("<GRP>") > -1)
{
state.sb.Remove(0,state.sb.Length);
Debug.WriteLine("Received group " +
content.Substring(0,1));
state.group = Convert.ToUInt16(content.Substring(0,1));
connectedClients.Add(state);

handler.BeginReceive(state.buffer, 0,
StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
else
{
Console.WriteLine("received something");
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0,
StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}

// Iterate through the connectedClients arraylist and send
// the data to clients who are in the right group
private static void sendToClients(string grp, string data)
{

try
{
foreach(StateObject s in connectedClients)
{
//StateObject so = (StateObject)connectedClients[i];
Debug.WriteLine("SendToClients: foreaching - " + grp +
" / " + s.group.ToString());
if(s.group.ToString() == grp)
{
Debug.WriteLine("IF");

//StateObject state = new StateObject();
//state.workSocket = s.workSocket;

byte[] byteData = Encoding.ASCII.GetBytes("test");

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

Debug.WriteLine("end if");
}
}
}
catch (Exception myExc)
{
Debug.WriteLine(myExc.Message);
}
}

private static void SendCallback(IAsyncResult ar)
{
Debug.WriteLine("SendCallBack called.");
try
{
StateObject state = (StateObject) ar.AsyncState;
Socket handler = state.workSocket;

// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);

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

byte[] byteData = Encoding.ASCII.GetBytes("");

handler.BeginReceive(byteData, 0, byteData.Length, 0,
new AsyncCallback(ReadCallback), state);

Debug.WriteLine("Called ReadCallBack after send");

}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

public static int Main(String[] args)
{
StartListening();
return 0;
}
}

I know this is a lot of code, but I'm hoping someone could wade through
there and see if they can help me. Based on the MSDN example for an
asynchronous socket server, I've tried to make the following app:

* users connect to the socket server in groups, specified when they send
an initial "n<GRP>" string, with n being the number of the group.
* when a user sends a string (ending in "<EOF>") to the server, it will
be bounced back to the other users in their group, no-one else.

It should be quite straightforward but I am just out of my depth. Please
help!
Nov 18 '05 #2
If you are not stuck to async - there is a TCP Server demo here that you can
easily build on:

http://www.atozed.com/indy/Demos/Indy10.iwp

Zip Code server
--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programming is an art form that fights back"
Nov 18 '05 #3
Chad Z. Hower aka Kudzu wrote:
If you are not stuck to async - there is a TCP Server demo here that you can
easily build on:

http://www.atozed.com/indy/Demos/Indy10.iwp

Zip Code server
--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programming is an art form that fights back"

Thanks. Part of the problem is that I don't know enough about this. I
just know what I want to create but not the underlying tech I need. So -
I don't know if I'm stuck to async, it's just what I stumbled upon.

I'll take a look at the demo, thanks.
Nov 18 '05 #4
Colin Ramsay <co*********@blueyonder.co.uk> wrote in
news:58*************@news-binary.blueyonder.co.uk:
Thanks. Part of the problem is that I don't know enough about this. I
just know what I want to create but not the underlying tech I need. So -
I don't know if I'm stuck to async, it's just what I stumbled upon.

I'll take a look at the demo, thanks.


Sync sockets are a LOT easier to work with. If you have any questions on the
demo let me know here.
--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programming is an art form that fights back"
Nov 18 '05 #5
This is a very cool socket demo:
http://www.mentalis.org/soft/projects/proxy/

--
Thanks,

Eric Lawrence
Program Manager
Assistance and Worldwide Services

This posting is provided "AS IS" with no warranties, and confers no rights.

"Colin" <co*********@blueyonder.co.uk> wrote in message
news:3b**************************@posting.google.c om...
I'm writing a little console socket server but I'm having some
difficulty. Can I ask your advice - where is the best place to get
some help on that topic? It would be nice if some people who knew what
they were doing could take a look at my code and tell me where and why
I'm going wrong.

Any suggestions of groups or forums?

Nov 18 '05 #6
Eric Lawrence [MSFT] wrote:
This is a very cool socket demo:
http://www.mentalis.org/soft/projects/proxy/


Reading through it now. Seems quite extensive. Wish I could find
something to guide me through this subject, but I will have to make do.

Thanks!
Nov 18 '05 #7
Feel free to chat with me off thread. Fiddler (www.fiddlertool.com) was
written in C# and makes extensive use of Sockets, so I may be able to help.

-Eric

"Colin Ramsay" <co*********@blueyonder.co.uk> wrote in message
news:lW****************@news-binary.blueyonder.co.uk...
Eric Lawrence [MSFT] wrote:
This is a very cool socket demo:
http://www.mentalis.org/soft/projects/proxy/


Reading through it now. Seems quite extensive. Wish I could find
something to guide me through this subject, but I will have to make do.

Thanks!

Nov 18 '05 #8

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

Similar topics

9
8655
by: Michael Lindsey | last post by:
I need to write a server app to send images to client GUIs that are outside of the server's domain. The client will have the file system path to the image but can not access the file system. I am...
4
2748
by: Macca | last post by:
I am writing an application that uses asynchronous sockets to get data over ethernet from embedded devices, up to 30 concurrent devices.(These devices are written in C). My application...
1
2540
by: Macca | last post by:
Hi, I am implementing an asynchronous socket server in my application. It will take data from connected clients and put it into a thread safe array that other threads in my application use. I...
2
6858
by: Macca | last post by:
My app has an asynchronous socket server. It will have 20 clients connected to the server. Each client sends data every 500 millisecondsThe Connections once established will not be closed unless...
0
4648
by: Macca | last post by:
Hi, I am writing an asychronous socket server to handle 20+ simulataneous connections. I have used the example in MSDN as a base. The code is shown at end of question. Each connection has a...
4
3590
by: Engineerik | last post by:
I am trying to create a socket server which will listen for connections from multiple clients and call subroutines in a Fortran DLL and pass the results back to the client. The asynchronous socket...
6
6985
by: Pat B | last post by:
Hi, I'm writing my own implementation of the Gnutella P2P protocol using C#. I have implemented it using BeginReceive and EndReceive calls so as not to block when waiting for data from the...
2
3411
by: Nicolas Le Gland | last post by:
Hello everyone here. This is my first post in this newsgroup, I hope I won't be to much off-topic. Feel free to redirect me to any better group. I am getting strange timing issues when...
1
7118
by: keksy | last post by:
Hi every1, I am writing a small client/server application and in it I want to send an image asynchronous from the client to the server through a TCP socket. I found an example code on the MSDN...
0
7202
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
7086
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
7330
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...
1
6991
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...
1
5014
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...
0
4672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3167
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3154
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1512
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.