Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. managing multiple socket connections !?

managing multiple socket connections !?

Scheduled Pinned Locked Moved C#
sysadmintutorialquestion
5 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • R Offline
    R Offline
    rareseu
    wrote on last edited by
    #1

    i have managed to make a client and server classes for socket comunication, but i have no ideea how to manage multiple clients connecting to the server, i've checked the web and msdn but most exmpales are either too convoluted or use different mechanics than mine, so how do you guys do this ?

    R 1 Reply Last reply
    0
    • R rareseu

      i have managed to make a client and server classes for socket comunication, but i have no ideea how to manage multiple clients connecting to the server, i've checked the web and msdn but most exmpales are either too convoluted or use different mechanics than mine, so how do you guys do this ?

      R Offline
      R Offline
      Ravadre
      wrote on last edited by
      #2

      rareseu wrote:

      i've checked the web and msdn but most exmpales are either too convoluted or use different mechanics than mine

      Maybe your mechanism isn't right then? :). 1. The simplest way is creating a thread that will call accept in a loop. For each accepted thread you create new client thread, pass new socket there and voila. Drawback is that you will use 1 socket per connection, so managing a lot of sockets could be expensive. (btw, for each client socket, you can use synchronous operations now). 2. A bit more complicated, but more robust solution is to use asynchrounous communication. Then, foreach connected client, you create him a read buffer, write buffer, supply callbacks methods and just invoke BeginRead/Write. Your callbacks methods will be ran automatically when some data will arive (read) or was sent (write). In callback methods, what you should do is call EndRead/Write to get data, do some quick processing (fe. copy received data to some external buffer) and invoke Begin methods once again, and so on, and so on :).

      R 1 Reply Last reply
      0
      • R Ravadre

        rareseu wrote:

        i've checked the web and msdn but most exmpales are either too convoluted or use different mechanics than mine

        Maybe your mechanism isn't right then? :). 1. The simplest way is creating a thread that will call accept in a loop. For each accepted thread you create new client thread, pass new socket there and voila. Drawback is that you will use 1 socket per connection, so managing a lot of sockets could be expensive. (btw, for each client socket, you can use synchronous operations now). 2. A bit more complicated, but more robust solution is to use asynchrounous communication. Then, foreach connected client, you create him a read buffer, write buffer, supply callbacks methods and just invoke BeginRead/Write. Your callbacks methods will be ran automatically when some data will arive (read) or was sent (write). In callback methods, what you should do is call EndRead/Write to get data, do some quick processing (fe. copy received data to some external buffer) and invoke Begin methods once again, and so on, and so on :).

        R Offline
        R Offline
        rareseu
        wrote on last edited by
        #3

        Thanks for the suggestions Ravadre :) I've got a question about the 2nd method and in fat this is the main thing i don't understand about working with sockets : how can i tell who i'm talking to ? (client wise) I mean if i accept a connection how do i know who's trying to connect to me ?

        R 1 Reply Last reply
        0
        • R rareseu

          Thanks for the suggestions Ravadre :) I've got a question about the 2nd method and in fat this is the main thing i don't understand about working with sockets : how can i tell who i'm talking to ? (client wise) I mean if i accept a connection how do i know who's trying to connect to me ?

          R Offline
          R Offline
          Ravadre
          wrote on last edited by
          #4

          I'm not sure if I understand your question correctly. If you meant that you don't know who has just connected to your server - well, you don't :), You can get his IP, or authentificate him using some sort of your own protocol. But if you would have meant that, then this is general issue, not only related to 2nd method, so maybe you've meant, how to know which client has sent you some data, which invoked your callback method, well, there are 2 ways to keep this information; when you Invoke BeginRead() you can pass your own parameter, you can pass some sort of structure that will tell you what you need to know, fe.: tcpClient.GetStream().BeginRead(buffer, 0, bufferSize, callback, this) then, in callback: TcpClient myClient = (TcpClient)result.AsyncState; The second approach (which I use) is to create some sort of wrapper class that handles everything, a little example (a bit simplified):

          public class Program
          {
          class NetClient
          {
          const int bufferSize = 4096;
          TcpClient client;
          byte[] writeBuffer;
          byte[] readBuffer;

          		public NetClient(TcpClient client)
          		{
          			this.client = client;
          			writeBuffer = new byte\[bufferSize\];
          			readBuffer = new byte\[bufferSize\];
          
          			client.GetStream().BeginRead(readBuffer, 0, bufferSize, OnDataRead, null);
          		}
          
          		void OnDataRead(IAsyncResult result)
          		{
          			int dataRead = client.GetStream().EndRead(result);
          
          			//...
          
          			client.GetStream().BeginRead(readBuffer, 0, bufferSize, OnDataRead, client);
          		}
          	}
          
          
          	public static void Main()
          	{
          		List<NetClient> clients = new List<NetClient>();
          
          		TcpListener server = new TcpListener(11111);
          
          		server.Start();
          
          		while (true)
          		{
          			TcpClient client = server.AcceptTcpClient();
          			Console.WriteLine((client.Client.RemoteEndPoint as IPEndPoint).Address);
          			clients.Add(new NetClient(client));
          		}
          	}
          

          }

          Alternatively, you could make OnDataRead static, and pass NetClient as a parameter, just like in 1st approach.

          R 1 Reply Last reply
          0
          • R Ravadre

            I'm not sure if I understand your question correctly. If you meant that you don't know who has just connected to your server - well, you don't :), You can get his IP, or authentificate him using some sort of your own protocol. But if you would have meant that, then this is general issue, not only related to 2nd method, so maybe you've meant, how to know which client has sent you some data, which invoked your callback method, well, there are 2 ways to keep this information; when you Invoke BeginRead() you can pass your own parameter, you can pass some sort of structure that will tell you what you need to know, fe.: tcpClient.GetStream().BeginRead(buffer, 0, bufferSize, callback, this) then, in callback: TcpClient myClient = (TcpClient)result.AsyncState; The second approach (which I use) is to create some sort of wrapper class that handles everything, a little example (a bit simplified):

            public class Program
            {
            class NetClient
            {
            const int bufferSize = 4096;
            TcpClient client;
            byte[] writeBuffer;
            byte[] readBuffer;

            		public NetClient(TcpClient client)
            		{
            			this.client = client;
            			writeBuffer = new byte\[bufferSize\];
            			readBuffer = new byte\[bufferSize\];
            
            			client.GetStream().BeginRead(readBuffer, 0, bufferSize, OnDataRead, null);
            		}
            
            		void OnDataRead(IAsyncResult result)
            		{
            			int dataRead = client.GetStream().EndRead(result);
            
            			//...
            
            			client.GetStream().BeginRead(readBuffer, 0, bufferSize, OnDataRead, client);
            		}
            	}
            
            
            	public static void Main()
            	{
            		List<NetClient> clients = new List<NetClient>();
            
            		TcpListener server = new TcpListener(11111);
            
            		server.Start();
            
            		while (true)
            		{
            			TcpClient client = server.AcceptTcpClient();
            			Console.WriteLine((client.Client.RemoteEndPoint as IPEndPoint).Address);
            			clients.Add(new NetClient(client));
            		}
            	}
            

            }

            Alternatively, you could make OnDataRead static, and pass NetClient as a parameter, just like in 1st approach.

            R Offline
            R Offline
            rareseu
            wrote on last edited by
            #5

            Thanks for taking the time to explain Ravadre :), i really appreciate it, i'm gonna need some research time to understand the classes and methods you're using. I guess the reason i'm being a little vague with my questions is because i'm not quite sure what i need to make this work, this is the first time i'm working with sockets under c# ( done it once before in c under linux )

            1 Reply Last reply
            0
            Reply
            • Reply as topic
            Log in to reply
            • Oldest to Newest
            • Newest to Oldest
            • Most Votes


            • Login

            • Don't have an account? Register

            • Login or register to search.
            • First post
              Last post
            0
            • Categories
            • Recent
            • Tags
            • Popular
            • World
            • Users
            • Groups