multi client to server in C#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jetean
    New Member
    • Feb 2008
    • 33

    multi client to server in C#

    Hi guys:
    This topic might sound very familiar to some of you, can some one shed some light or point me to some web link for some sample code or good guide?

    I'm able to code for a simple client to server ( one to one) but not this multi client scenario.

    The application that i want to establish is simple:

    clientx.1--------------> send a request to server for a job
    clientx.2--------------> send a request to server for another job
    ..
    ....

    all this activities have to be concurrent...

    how to do this?


    Thanks
  • Ramk
    New Member
    • Nov 2008
    • 61

    #2
    Originally posted by Jetean
    Hi guys:
    This topic might sound very familiar to some of you, can some one shed some light or point me to some web link for some sample code or good guide?

    I'm able to code for a simple client to server ( one to one) but not this multi client scenario.

    The application that i want to establish is simple:

    clientx.1--------------> send a request to server for a job
    clientx.2--------------> send a request to server for another job
    ..
    ....

    all this activities have to be concurrent...

    how to do this?


    Thanks
    Use ThreadPool wherein you can run your client(s) separately on thread(s).
    ie clientx.1-> will run on Thread1
    clientx.2-> will run on Thread2...

    Comment

    • Jetean
      New Member
      • Feb 2008
      • 33

      #3
      Hi:

      Are you suggesting to have multiple server running on multiple thread?

      Is this viable?

      Thanks

      Comment

      • Ramk
        New Member
        • Nov 2008
        • 61

        #4
        Originally posted by Jetean
        Hi:

        Are you suggesting to have multiple server running on multiple thread?

        Is this viable?

        Thanks
        No no... Its about client. You can have your client on a separate thread which communicates to the server. If you have common resources across the clients, you may have to opt synchronization between your clients.

        Comment

        • mldisibio
          Recognized Expert New Member
          • Sep 2008
          • 191

          #5
          Can you please clarify what design you are using for "client/server."
          Are you using Remoting, WebServices, or hand-coded socket communication?

          Are these truly separate clients talking to one server in a separately compiled server application or listener?

          If so, what protocol do you use to send and receive job requests?

          Mike

          Comment

          • Jetean
            New Member
            • Feb 2008
            • 33

            #6
            OK. I'm using Socket. The application is to serve multiple PCs within the same office. 1 server and multiple clients. I think i can handle the client side but I'm not sure about the Server side program. How to do it?

            Comment

            • Jetean
              New Member
              • Feb 2008
              • 33

              #7
              One more condition is that The Server has to continously scan for any new connection and new incoming request..

              Comment

              • mldisibio
                Recognized Expert New Member
                • Sep 2008
                • 191

                #8
                For the listener, I would suggest you start by studying the System.Net.Sock ets.TcpListener class, as this will take care much of the infrastructure of listening for socket connection requests and reading them.

                Comment

                • Jetean
                  New Member
                  • Feb 2008
                  • 33

                  #9
                  mldisibio:
                  I'm looking at Asynchronous TCP Server. I'm not quite sure how to implement it. With many Clients sending data back to Server, Will one Client Keep Connected to the server preventing access from other Clients?

                  Comment

                  • Ramk
                    New Member
                    • Nov 2008
                    • 61

                    #10
                    Is it something like your TCP SERVER(which you will be developing) has to perform normal tasks(irrespect ive of the operations) along with SERVING YOUR CLIENTS(each client is a separate PC)! Are you seeking Asynchronus SERVER for this purpose?

                    Comment

                    • JosAH
                      Recognized Expert MVP
                      • Mar 2007
                      • 11453

                      #11
                      The 'de facto' way to do this is to run a simple loop that accepts new clients. Once accepted the new socket/client is passed to a new thread that serves the client through that socket. Once done, the thread simply dies. Shared resources should be synchronized among the several client serving threads.

                      kind regards,

                      Jos

                      Comment

                      • Plater
                        Recognized Expert Expert
                        • Apr 2007
                        • 7872

                        #12
                        Jos is actually right (pause for recovery of blockbuster news).

                        Generally, you will have thread that sets up the listener socket, loops around accepting connections (syncronous or asyncronous), and starts a new thread for each new connection.
                        Thread loop should take steps to not be a busy loop.

                        Each of your spawned threads will handle interaction with the connected client.

                        This is similar to the way a webserver works.

                        Comment

                        • moii
                          New Member
                          • May 2014
                          • 6

                          #13
                          Code:
                          using System;
                          using System.Collections.Generic;
                          using System.ComponentModel;
                          using System.Data;
                          using System.Drawing;
                          using System.Linq;
                          using System.Text;
                          using System.Windows.Forms;
                          
                          using System.Net;
                          using System.Net.Sockets;
                          using System.Diagnostics;
                          
                          using System.IO;
                          
                          namespace Server
                          {
                          	public partial class ServerForm : Form
                          	{
                          		Dictionary<string, string> dictionary;
                          
                          		const int BUFFER_SIZE = 1024;
                          		byte[] rcvBuffer = new byte[BUFFER_SIZE];	// To recieve data from the client
                          
                          		Socket serverSocket;
                          		int socketCounter = 0;
                          		Dictionary<Socket, int> clientSocketDictionary = new Dictionary<Socket, int>();
                          
                          		const int PORT = 3333;
                          
                          		public ServerForm()
                          		{
                          			InitializeComponent();
                          			FillDictionary();
                          			StartServer();
                          		}
                          
                          		//Construct server socket and bind it to all local netowrk interfaces, then listen for connections
                          		void StartServer()
                          		{
                          			try
                          			{
                          				serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                          				serverSocket.Bind(new IPEndPoint(IPAddress.Any, PORT));
                          				serverSocket.Listen(10);	// Listen(10) means we can handle
                          											// 10 clients requests simultaneously
                          				serverSocket.BeginAccept(AcceptCallback, null);
                          			}
                          			catch (Exception ex) { AppendToTextBox(ex.Message); }
                          		}
                          Last edited by Rabbit; May 25 '14, 09:22 PM. Reason: Please use [code] and [/code] tags when posting code or formatted data.

                          Comment

                          • moii
                            New Member
                            • May 2014
                            • 6

                            #14
                            you must determine the client ip first !

                            Comment

                            • moii
                              New Member
                              • May 2014
                              • 6

                              #15
                              Code:
                              void AcceptCallback(IAsyncResult AR)
                              		{
                              			try
                              			{
                              				Socket tempSocket = serverSocket.EndAccept(AR);	// Client connected successfully, waiting for requests
                              
                              				tempSocket.BeginReceive(rcvBuffer, 0, rcvBuffer.Length, SocketFlags.None, ReceiveCallback, tempSocket);
                              
                              				socketCounter++;
                              				clientSocketDictionary.Add(tempSocket, socketCounter);
                              
                              				AppendToTextBox("Client " + socketCounter + " connected successfully...");
                              				
                              				byte[] replyBuffer = Encoding.ASCII.GetBytes("Connected successfully...");
                              				tempSocket.Send(replyBuffer);
                              				
                              				serverSocket.BeginAccept(AcceptCallback, null);
                              			}
                              
                              			catch (Exception ex) { AppendToTextBox(ex.Message); }
                              		}
                              
                              		void ReceiveCallback(IAsyncResult AR)
                              		{
                              			Socket tempSocket = (Socket)AR.AsyncState;
                              			int bytesReceived = 0;
                              			int clientNumber = clientSocketDictionary[tempSocket];
                              
                              			try
                              			{
                              				bytesReceived = tempSocket.EndReceive(AR);	// Get number of bytes received
                              			}
                              			catch (Exception ex)
                              			{
                              				AppendToTextBox("Exception: " + ex.Message + "...");
                              				tempSocket.Close();
                              				clientSocketDictionary.Remove(tempSocket);
                              			}
                              
                              			if (bytesReceived > 0)
                              			{
                              				byte[] rcvBufferTrim = new byte[bytesReceived];
                              				Array.Copy(rcvBuffer, rcvBufferTrim, bytesReceived);	// Removes trailing nulls
                              				string rcvText = Encoding.ASCII.GetString(rcvBufferTrim);	// Convert bytes into string
                              				rcvText = rcvText.ToLower().ToString();
                              
                              				string replyText = "";
                              				DateTime time = DateTime.Now;
                              
                              				#region Switch statement for received text, check for special requests
                              				switch (rcvText)
                              				{
                              					case "gettime":
                              						AppendToTextBox("Received from client [" + clientNumber.ToString() + "]: " + rcvText);
                              						replyText = "Time is : " + time.ToString("HH:MM:ss");
                              						break;
                              					case "getdate":
                              						AppendToTextBox("Received from client [" + clientNumber.ToString() + "]: " + rcvText);
                              						replyText = "Date is : " + time.ToString("dd/mm/yyyy");
                              						break;
                              					case "disconnect":
                              						tempSocket.Shutdown(SocketShutdown.Both);
                              						tempSocket.Close();
                              						clientSocketDictionary.Remove(tempSocket);
                              						AppendToTextBox("Client [" + clientNumber.ToString() + "] closed connection");
                              						return;
                              					default:
                              						AppendToTextBox("Received from client [" + clientNumber.ToString() + "]: " + rcvText);
                              						if (dictionary.ContainsKey(rcvText))
                              							replyText = dictionary[rcvText];
                              						else
                              							replyText = "Not Found";
                              						break;
                              				}
                              				#endregion
                              
                              				// Send the reply text
                              				byte[] replyBuffer = Encoding.ASCII.GetBytes(replyText);
                              				tempSocket.Send(replyBuffer);
                              
                              				// Starts receiving data again
                              				tempSocket.BeginReceive(rcvBuffer, 0, rcvBuffer.Length,
                              					SocketFlags.None, new AsyncCallback(ReceiveCallback), tempSocket);
                              			}
                              			else
                              			{
                              				try
                              				{
                              					tempSocket.Shutdown(SocketShutdown.Both);
                              					tempSocket.Close();
                              					clientSocketDictionary.Remove(tempSocket);
                              					AppendToTextBox("Client [" + clientNumber.ToString() + "] closed connection");
                              				}
                              				catch { AppendToTextBox("Client [" + clientNumber.ToString() + "] closed connection"); }
                              			}
                              		}
                              
                              		// Provides a thread-safe way to append text to the textbox
                              		void AppendToTextBox(string text)
                              		{
                              			MethodInvoker invoker = new MethodInvoker(delegate
                              			{
                              				textBox.Text += text + "\r\n";
                              				textBox.SelectionStart = textBox.TextLength;
                              				textBox.ScrollToCaret();
                              			});	// "\r\n" are for new lines
                              			this.Invoke(invoker);
                              		}
                              
                              		// Add all entries to fill the dictionary
                              		void FillDictionary()
                              		{
                              			string[] lines = File.ReadAllLines("IPaddresses.txt");
                              			dictionary = lines.Select(l => l.Split(':')).ToDictionary(a => a[0], a => a[1]);
                              		}
                              
                                      private void textBox_TextChanged(object sender, EventArgs e)
                                      {
                              
                                      }
                              	}
                              }
                              Last edited by Rabbit; May 25 '14, 09:22 PM. Reason: Please use [code] and [/code] tags when posting code or formatted data.

                              Comment

                              Working...