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
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. client/server problem [modified]

client/server problem [modified]

Scheduled Pinned Locked Moved C#
comsysadminhostinghelptutorial
9 Posts 2 Posters 3 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.
  • S Offline
    S Offline
    staticv
    wrote on last edited by
    #1

    I have developed a simple client/server app which echoes whatever text the clients sends to the server. Currently, it echoes text only to one client, which has send the text, but I want it to send to all the clients connected. The problem is that when one client writes to the server after that the client waits for receiving and as soon it has received the echo it starts writing to the server, so if some other client sends to the server, and the server echoes back to all the clients, only those will receive the message which are waiting for reading, but none are except the client which has send the message to the server. So how to overcome this? Btw, it is a console application, is it possible to do in it? I guess I explained it correctly. If not, then please ask again :)

    Top Web Hosting Providers[^] Do, or do not. There is no 'try'.

    modified on Monday, January 26, 2009 9:59 AM

    M 1 Reply Last reply
    0
    • S staticv

      I have developed a simple client/server app which echoes whatever text the clients sends to the server. Currently, it echoes text only to one client, which has send the text, but I want it to send to all the clients connected. The problem is that when one client writes to the server after that the client waits for receiving and as soon it has received the echo it starts writing to the server, so if some other client sends to the server, and the server echoes back to all the clients, only those will receive the message which are waiting for reading, but none are except the client which has send the message to the server. So how to overcome this? Btw, it is a console application, is it possible to do in it? I guess I explained it correctly. If not, then please ask again :)

      Top Web Hosting Providers[^] Do, or do not. There is no 'try'.

      modified on Monday, January 26, 2009 9:59 AM

      M Offline
      M Offline
      Mustafa Ismail Mustafa
      wrote on last edited by
      #2

      It sounds like you're trying to emulate a group chat/IM session. You're going to need to register all the users who "log" on to your server and are interested in the echo. The Observer pattern is precisely what you are looking for: http://www.dofactory.com/Patterns/PatternObserver.aspx[^] and http://en.wikipedia.org/wiki/Observer_pattern[^] After reading that you should have a clue of what you ought to do but in plain English what you're doing is that you're making a list of all the registrants and instead of echoing to one, you're broadcasting the echo to each and everyone in the list. Post back if you need more help.

      S 1 Reply Last reply
      0
      • M Mustafa Ismail Mustafa

        It sounds like you're trying to emulate a group chat/IM session. You're going to need to register all the users who "log" on to your server and are interested in the echo. The Observer pattern is precisely what you are looking for: http://www.dofactory.com/Patterns/PatternObserver.aspx[^] and http://en.wikipedia.org/wiki/Observer_pattern[^] After reading that you should have a clue of what you ought to do but in plain English what you're doing is that you're making a list of all the registrants and instead of echoing to one, you're broadcasting the echo to each and everyone in the list. Post back if you need more help.

        S Offline
        S Offline
        staticv
        wrote on last edited by
        #3

        Well, whenever a user is connected I store its connection and username in a hashtable, and when the server receives a message, I create a for loop and gets everyone's specific stream and then send the message to them. But at that time the clients are waiting for the input, rather than reading what the server has send. Only that client reads who have send the message to the server. Do you want me to post the code? Heres the code for the server

        using System;
        using System.Net;
        using System.Net.Sockets;
        using System.IO;
        using System.Threading;
        using System.Collections;
        using System.Text;

        public class ClientHandler
        {
        public TcpClient clientSocket;

        public void RunClient()
        {
        // Create the stream classes
        StreamReader readerStream = new StreamReader(clientSocket.GetStream());
        NetworkStream writerStream = clientSocket.GetStream();

          string returnData = readerStream.ReadLine(); 
          string userName = returnData; 
        
          Console.WriteLine("Welcome " + userName + " to the Server"); 
        
          while (true) 
          { 
             returnData = readerStream.ReadLine(); 
        
             if (returnData.IndexOf("QUIT") > −1) 
             { 
                Console.WriteLine("Bye Bye " + userName); 
                break; 
             } 
        
             Console.WriteLine(userName + ": " + returnData); 
             returnData += "\\r\\n"; 
        
             byte\[\] dataWrite = Encoding.ASCII.GetBytes(returnData) 
             writerStream.Write(dataWrite,0,dataWrite.Length); 
          } 
        
          clientSocket.Close(); 
        

        }
        }

        public class EchoServer
        {
        const int ECHO_PORT = 8080;

        public static void Main(string [] arg)
        {
        try
        {
        // Bind the server to the local port
        TcpListener clientListener = new TcpListener(ECHO_PORT);

             // Start to listen 
             clientListener.Start(); 
        
             Console.WriteLine("Waiting for connections…"); 
        
             while (true) 
             { 
                // Accept the connection 
                TcpClient client = clientListener.AcceptTcpClient(); 
        
                ClientHandler cHandler = new ClientHandler(); 
        
                // Pass value to the ClientHandler object 
                cHandler.clientSocket = client; 
        
                // Create a new thread for the client 
                Thread clientThread = new Thread(new ThreadStart(cHandler.RunClient)); 
                clientThread.Start(); 
             } 
        
             clientListener.Stop(); 
          } 
          catch(Exception exp)
        
        M 1 Reply Last reply
        0
        • S staticv

          Well, whenever a user is connected I store its connection and username in a hashtable, and when the server receives a message, I create a for loop and gets everyone's specific stream and then send the message to them. But at that time the clients are waiting for the input, rather than reading what the server has send. Only that client reads who have send the message to the server. Do you want me to post the code? Heres the code for the server

          using System;
          using System.Net;
          using System.Net.Sockets;
          using System.IO;
          using System.Threading;
          using System.Collections;
          using System.Text;

          public class ClientHandler
          {
          public TcpClient clientSocket;

          public void RunClient()
          {
          // Create the stream classes
          StreamReader readerStream = new StreamReader(clientSocket.GetStream());
          NetworkStream writerStream = clientSocket.GetStream();

            string returnData = readerStream.ReadLine(); 
            string userName = returnData; 
          
            Console.WriteLine("Welcome " + userName + " to the Server"); 
          
            while (true) 
            { 
               returnData = readerStream.ReadLine(); 
          
               if (returnData.IndexOf("QUIT") > −1) 
               { 
                  Console.WriteLine("Bye Bye " + userName); 
                  break; 
               } 
          
               Console.WriteLine(userName + ": " + returnData); 
               returnData += "\\r\\n"; 
          
               byte\[\] dataWrite = Encoding.ASCII.GetBytes(returnData) 
               writerStream.Write(dataWrite,0,dataWrite.Length); 
            } 
          
            clientSocket.Close(); 
          

          }
          }

          public class EchoServer
          {
          const int ECHO_PORT = 8080;

          public static void Main(string [] arg)
          {
          try
          {
          // Bind the server to the local port
          TcpListener clientListener = new TcpListener(ECHO_PORT);

               // Start to listen 
               clientListener.Start(); 
          
               Console.WriteLine("Waiting for connections…"); 
          
               while (true) 
               { 
                  // Accept the connection 
                  TcpClient client = clientListener.AcceptTcpClient(); 
          
                  ClientHandler cHandler = new ClientHandler(); 
          
                  // Pass value to the ClientHandler object 
                  cHandler.clientSocket = client; 
          
                  // Create a new thread for the client 
                  Thread clientThread = new Thread(new ThreadStart(cHandler.RunClient)); 
                  clientThread.Start(); 
               } 
          
               clientListener.Stop(); 
            } 
            catch(Exception exp)
          
          M Offline
          M Offline
          Mustafa Ismail Mustafa
          wrote on last edited by
          #4

          Three things: 1. Did you read the literature I posted? It'll really help you 2. Why are you using a Hashtable? 3. cHandler.clientSocket = client; See this? You're only ever responding to one and one client at any time, and if you don't mind me saying it, you're doing a bad job of it. Read the literature, it'll show you a really good way of doing things.

          S 1 Reply Last reply
          0
          • M Mustafa Ismail Mustafa

            Three things: 1. Did you read the literature I posted? It'll really help you 2. Why are you using a Hashtable? 3. cHandler.clientSocket = client; See this? You're only ever responding to one and one client at any time, and if you don't mind me saying it, you're doing a bad job of it. Read the literature, it'll show you a really good way of doing things.

            S Offline
            S Offline
            staticv
            wrote on last edited by
            #5

            sorry I posted the old code :) heres the modified one where i send messages to all. btw i'm going to read the article you given while you tell me if the code is correct or not :)

            void RunClient()
            {
            	// Create the stream classes
            	StreamReader readerStream = new StreamReader(clientSocket.GetStream());
            	NetworkStream writerStream = clientSocket.GetStream();
            
            	string returnData = readerStream.ReadLine();
            	string userName = returnData;
            	
            	// Add a user
            	users.Add(userName, clientSocket);
            
            	Console.WriteLine("Welcome " + userName + " to the Server");
            
            	while (true)
            	{
            		returnData = readerStream.ReadLine();
            		String tempData = returnData.ToLower();
            
            		if (tempData.IndexOf("quit") > -1)
            		{
            			Console.WriteLine("Bye Bye " + userName);
            			break;
            		}
            
            		Console.WriteLine(userName + ": " + returnData);
            		returnData += "\\r\\n";
            
            		byte\[\] dataWrite = Encoding.ASCII.GetBytes(returnData);
            		
            		TcpClient\[\] tcpClients = new TcpClient\[users.Count\];
            		users.Values.CopyTo(tcpClients, 0);
            		for (int i = 0; i < tcpClients.Length; i++)
            		{
            			NetworkStream tempWriteStream = tcpClients\[i\].GetStream();
            			tempWriteStream.Write(dataWrite, 0, dataWrite.Length);
            			tempWriteStream = null;
            		}
            	}
            
            	clientSocket.Close();
            }
            

            Top Web Hosting Providers[^] Do, or do not. There is no 'try'.

            modified on Monday, January 26, 2009 10:43 AM

            M 1 Reply Last reply
            0
            • S staticv

              sorry I posted the old code :) heres the modified one where i send messages to all. btw i'm going to read the article you given while you tell me if the code is correct or not :)

              void RunClient()
              {
              	// Create the stream classes
              	StreamReader readerStream = new StreamReader(clientSocket.GetStream());
              	NetworkStream writerStream = clientSocket.GetStream();
              
              	string returnData = readerStream.ReadLine();
              	string userName = returnData;
              	
              	// Add a user
              	users.Add(userName, clientSocket);
              
              	Console.WriteLine("Welcome " + userName + " to the Server");
              
              	while (true)
              	{
              		returnData = readerStream.ReadLine();
              		String tempData = returnData.ToLower();
              
              		if (tempData.IndexOf("quit") > -1)
              		{
              			Console.WriteLine("Bye Bye " + userName);
              			break;
              		}
              
              		Console.WriteLine(userName + ": " + returnData);
              		returnData += "\\r\\n";
              
              		byte\[\] dataWrite = Encoding.ASCII.GetBytes(returnData);
              		
              		TcpClient\[\] tcpClients = new TcpClient\[users.Count\];
              		users.Values.CopyTo(tcpClients, 0);
              		for (int i = 0; i < tcpClients.Length; i++)
              		{
              			NetworkStream tempWriteStream = tcpClients\[i\].GetStream();
              			tempWriteStream.Write(dataWrite, 0, dataWrite.Length);
              			tempWriteStream = null;
              		}
              	}
              
              	clientSocket.Close();
              }
              

              Top Web Hosting Providers[^] Do, or do not. There is no 'try'.

              modified on Monday, January 26, 2009 10:43 AM

              M Offline
              M Offline
              Mustafa Ismail Mustafa
              wrote on last edited by
              #6

              OK, this is in the wrong forum now.

              S 1 Reply Last reply
              0
              • M Mustafa Ismail Mustafa

                OK, this is in the wrong forum now.

                S Offline
                S Offline
                staticv
                wrote on last edited by
                #7

                no, i changed the code :)

                Top Web Hosting Providers[^] Do, or do not. There is no 'try'.

                M 1 Reply Last reply
                0
                • S staticv

                  no, i changed the code :)

                  Top Web Hosting Providers[^] Do, or do not. There is no 'try'.

                  M Offline
                  M Offline
                  Mustafa Ismail Mustafa
                  wrote on last edited by
                  #8

                  You did, from C# to C++/CLI which makes it in the wrong forum

                  S 1 Reply Last reply
                  0
                  • M Mustafa Ismail Mustafa

                    You did, from C# to C++/CLI which makes it in the wrong forum

                    S Offline
                    S Offline
                    staticv
                    wrote on last edited by
                    #9

                    it is C# :)

                    Top Web Hosting Providers[^] Do, or do not. There is no 'try'.

                    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