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? 7 2386
I'll just post some code here in case anyone fancies a look:
using System;
using System.Net;
using System.Net.Sock ets;
using System.Text;
using System.Threadin g;
using System.Collecti ons;
using System.Diagnost ics;
// 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 AsynchronousSoc ketListener
{
public static int currentGroup = 0;
public static ArrayList connectedClient s = new ArrayList();
public static ArrayList connectedClient Groups = new ArrayList();
public static string grp = string.Empty;
// Incoming data from client.
public static string data = null;
// Thread signal.
public static ManualResetEven t allDone = new ManualResetEven t(false);
public AsynchronousSoc ketListener()
{
}
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.c om".
IPHostEntry ipHostInfo = Dns.Resolve(Dns .GetHostName()) ;
IPAddress ipAddress = ipHostInfo.Addr essList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAd dress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p );
// Bind the socket to the local endpoint and listen for
incoming connections.
try
{
listener.Bind(l ocalEndPoint);
listener.Listen (100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset() ;
// Start an asynchronous socket to listen for connections.
Console.WriteLi ne("Waiting for a connection...") ;
// (method, object)
listener.BeginA ccept(new AsyncCallback(A cceptCallback),
listener);
// Wait until a connection is made before continuing.
allDone.WaitOne ();
}
}
catch (Exception e)
{
Console.WriteLi ne(e.ToString() );
}
Console.WriteLi ne("\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.EndAcc ept(ar);
// Add this newly connected client socket to our arraylist
// Create the state object - CUSTOM OBJECT!
StateObject state = new StateObject();
state.workSocke t = handler;
handler.BeginRe ceive( state.buffer, 0, StateObject.Buf ferSize, 0,
new AsyncCallback(R eadCallback), state);
}
// this is basically constantly called
public static void ReadCallback(IA syncResult ar)
{
Console.WriteLi ne("ReadCallBac k");
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.workSocke t;
// Read data from the client socket.
int bytesRead = handler.EndRece ive(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.ToStri ng();
if (content.IndexO f("<EOF>") > -1)
{
state.sb.Remove (0,state.sb.Len gth);
// All the data has been read from the
// client. Display it on the console.
Console.WriteLi ne("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(s tate.group.ToSt ring(), content);
}
// initial string will be the group this client is attached to
// this will be the first to be called.
else if (content.IndexO f("<GRP>") > -1)
{
state.sb.Remove (0,state.sb.Len gth);
Debug.WriteLine ("Received group " +
content.Substri ng(0,1));
state.group = Convert.ToUInt1 6(content.Subst ring(0,1));
connectedClient s.Add(state);
handler.BeginRe ceive(state.buf fer, 0,
StateObject.Buf ferSize, 0,
new AsyncCallback(R eadCallback), state);
}
else
{
Console.WriteLi ne("received something");
// Not all data received. Get more.
handler.BeginRe ceive(state.buf fer, 0,
StateObject.Buf ferSize, 0,
new AsyncCallback(R eadCallback), state);
}
}
}
// Iterate through the connectedClient s arraylist and send
// the data to clients who are in the right group
private static void sendToClients(s tring grp, string data)
{
try
{
foreach(StateOb ject s in connectedClient s)
{
//StateObject so = (StateObject)co nnectedClients[i];
Debug.WriteLine ("SendToClients : foreaching - " + grp +
" / " + s.group.ToStrin g());
if(s.group.ToSt ring() == grp)
{
Debug.WriteLine ("IF");
//StateObject state = new StateObject();
//state.workSocke t = s.workSocket;
byte[] byteData = Encoding.ASCII. GetBytes("test" );
// Begin sending the data to the remote device.
s.workSocket.Be ginSend(byteDat a, 0, byteData.Length , 0,
new AsyncCallback(S endCallback), s);
Debug.WriteLine ("end if");
}
}
}
catch (Exception myExc)
{
Debug.WriteLine (myExc.Message) ;
}
}
private static void SendCallback(IA syncResult ar)
{
Debug.WriteLine ("SendCallBa ck called.");
try
{
StateObject state = (StateObject) ar.AsyncState;
Socket handler = state.workSocke t;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend (ar);
Console.WriteLi ne("Sent {0} bytes to client.", bytesSent);
//handler.Shutdow n(SocketShutdow n.Both);
//handler.Close() ;
byte[] byteData = Encoding.ASCII. GetBytes("");
handler.BeginRe ceive(byteData, 0, byteData.Length , 0,
new AsyncCallback(R eadCallback), state);
Debug.WriteLine ("Called ReadCallBack after send");
}
catch (Exception e)
{
Console.WriteLi ne(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!
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/ "Programmin g 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.
Colin Ramsay <co*********@bl ueyonder.co.uk> wrote in
news:58******** *****@news-binary.blueyond er.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/
"Programmin g is an art form that fights back"
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*********@bl ueyonder.co.uk> wrote in message
news:3b******** *************** ***@posting.goo gle.com... 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?
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!
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*********@bl ueyonder.co.uk> wrote in message
news:lW******** ********@news-binary.blueyond er.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! This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 trying to decide if I should use remoting vs. writing a server that
uses networkstreams.
I have read that networkstreams\tcp programming should be faster than
remoting and is a better choice for what I am doing but that it is difficult
to code.
|
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 implements an asychronous socket server while the embedded
devices are the clients
When the data comes in over the socket it is eventually passed into a
message queue.
|
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 need to allow other threads in my application to communicate with the
Socket server to send data back to the clients.
I'm not sure what the most efficent method is to do this.
|
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 there is a problem with the
connection.
I need to know which client has sent the incoming data as each client has
its own buffer on my "server" app.
I am using the standard asynch socket code from MSDN to listen for
connections and they...
|
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 number of different types of data coming in. I have a
databuffer for each type of data coming in.
| |
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 client and asynchronous socket
server example code provided in the .NET framework developers guide is a
great start but I have not dealt with sockets before and I am struggling with
something.
From what I can tell the sample server code ...
|
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 supernode.
Everything I have written works fine sending and receiving
uncompressed data. But now I want to implement compression using the
deflate algorithm as the Gnutella protocol accepts:
Accept-Encoding: deflate
Content-Encoding: deflate
in the...
|
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 failing to asynchronously connect
sockets on closed or filtered ports, but I'm quite unsure if this is a PHP
issue or my misunderstanding, as it seems that socket streams only wrap
around <sys/socket.h>.
|
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 site, which is actually
for sending strings. I tried to adapt this code so that the client
sends an image instead of a string. However, there is something wrong
on the server side (i guess)...
The server starts listening, the client starts sending...
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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 then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
| |
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 we have to send another system
| |