locked
TCP Server - Messages to Clients

    Question

  • Hi,

    Am learning C#, an I've come to TCP Servers, but I have hit a dead end on my playing around.

    I have the code below and it works fine, I have a GUI client and it can send messages to the server, I am able to connect more than one client and they are both able to talk to the server.

    My question is how do I make the server send all the data it gets to the clients?

    Here is the code I have so far;

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    
    namespace TCPServer
    {
      class Program
      {
        static void Main(string[] args)
        {
          ThreadedTcpSrvr server = new ThreadedTcpSrvr();
        }
      }
    
    
      class ThreadedTcpSrvr
      {
        private TcpListener client;
        public ThreadedTcpSrvr()
        {
          client = new TcpListener(9050);
    
          //the Start() method to begin waiting for new clients
          client.Start();
          Console.WriteLine("Waiting for clients...");
    
          //This infinite loop, checking once every second to see if a client 
          //has connected and, if it has, creating a new thread to accept the  //connection
    
          while (true)
          {
            while (!client.Pending())
            {
              Thread.Sleep(1000);
            }
            ConnectionThread newconnection = new ConnectionThread();
            newconnection.threadListener = this.client;
            Thread newthread = new Thread(new ThreadStart(newconnection.HandleConnection));
            newthread.Start();
          }
        }
      }
    
    
      class ConnectionThread
      {
        public TcpListener threadListener;
        private static int connections = 0;
        public void HandleConnection()
        {
          int recv;
          byte[] data = new byte[1024];
          TcpClient client = threadListener.AcceptTcpClient();
          NetworkStream ns = client.GetStream();
    
          // Counts the number of connections
          connections++;
    
          // Writes to the console when a client connects
          Console.WriteLine("New client accepted: {0} active connections",connections);
    
          // Sets the welcome message
          string welcome = "Welcome to the Secure Server";
    
          // Encodes welcome messages and sets it as a var
          data = Encoding.ASCII.GetBytes(welcome);
    
          // Send welcome message to client
          ns.Write(data, 0, data.Length);
    
          while (true)
          {
            data = new byte[1024];
            recv = ns.Read(data, 0, data.Length);
            if (recv == 0)
              break;
    
            // Writes the messages the client sends to the server
            Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
    
    
            ns.Write(data, 0, recv);
          }
          ns.Close();
          client.Close();
          connections--;
          Console.WriteLine("Client disconnected: {0} active connections",connections);
        }
      }
    }
    

    The aim is to move from a console to a windows form but one step at a time...

    Thanks for any help and guidance.

    Karl

    Friday, February 18, 2011 1:23 PM

Answers

  • Check out the code bollow, which using TcpListener (for server) and TclClient (for client). There is the code for the client and server - which includes the code for sending messages to all the clients (different kind of messages).
    //The client:
    
    using System.IO; 
    using System.Net; 
    using System; 
    using System.Threading; 
    using N = System.Net; 
    using System.Collections; 
    using System.Windows.Forms; 
    using System.ComponentModel; 
    using System.Runtime.InteropServices; 
    
    class TalkUser 
    { 
     static Form talk; 
     static N.Sockets.TcpClient TC; 
    
     [DllImport("kernel32.dll")] 
     private static extern void ExitProcess(int a); 
     
     public static void Main() { 
      talk = new Form(); 
      talk.Text = "TalkUser - The OFFICIAL TalkServ Client"; 
      talk.Closing += new CancelEventHandler(talk_Closing); 
      talk.Controls.Add(new TextBox()); 
      talk.Controls[0].Dock = DockStyle.Fill; 
      talk.Controls.Add(new TextBox()); 
      talk.Controls[1].Dock = DockStyle.Bottom; 
      ((TextBox)talk.Controls[0]).Multiline = true; 
      ((TextBox)talk.Controls[1]).Multiline = true; 
      talk.WindowState = FormWindowState.Maximized; 
      talk.Show(); 
      ((TextBox)talk.Controls[1]).KeyUp += new KeyEventHandler(key_up); 
      TC = new N.Sockets.TcpClient(); 
      TC.Connect("IP OF A SERVER HERE",4296); 
      Thread t = new Thread(new ThreadStart(run)); 
      t.Start(); 
      while(true) { 
       Application.DoEvents(); 
      } 
     } 
     
     private static void talk_Closing(object s, CancelEventArgs e) { 
      e.Cancel = false; 
      Application.Exit(); 
      ExitProcess(0); 
     } 
     
     private static void key_up(object s,KeyEventArgs e) { 
      TextBox TB = (TextBox)s; 
      if(TB.Lines.Length>1) { 
       StreamWriter SW = new StreamWriter(TC.GetStream()); 
       SW.WriteLine(TB.Text); 
       SW.Flush(); 
       TB.Text = ""; 
       TB.Lines = null; 
      } 
     } 
     
     private static void run() { 
      StreamReader SR = new StreamReader(TC.GetStream()); 
      while(true) { 
       Application.DoEvents(); 
       TextBox TB = (TextBox)talk.Controls[0]; 
       TB.AppendText(SR.ReadLine()+"\r\n"); 
       TB.SelectionStart = TB.Text.Length; 
      } 
     } 
    }
    
    //And the server:
    
    using System.IO; 
    using System.Net; 
    using System; 
    using System.Threading; 
    using N = System.Net; 
    using System.Collections; 
    
    class TalkServ { 
     
     System.Net.Sockets.TcpListener server; 
     public static Hashtable handles; 
     public static Hashtable handleByConnect; 
     
     public static void Main() { 
      TalkServ TS = new TalkServ(); 
     } 
    
     public TalkServ() { 
      handles = new Hashtable(100); 
      handleByConnect = new Hashtable(100); 
      server = new System.Net.Sockets.TcpListener(4296); 
      while(true) { 
       server.Start(); 
       if(server.Pending()) { 
        N.Sockets.TcpClient connection = server.AcceptTcpClient(); 
        Console.WriteLine("Connection made"); 
        BackForth BF = new BackForth(connection);    
       } 
      } 
     } 
     
     public static void SendToAll(string name,string msg) { 
      StreamWriter SW; 
      ArrayList ToRemove = new ArrayList(0); 
      N.Sockets.TcpClient[] tc = new N.Sockets.TcpClient[TalkServ.handles.Count]; 
      TalkServ.handles.Values.CopyTo(tc,0); 
      for(int i=0;i<tc.Length;i++) { 
       try { 
       if(msg.Trim()==""||tc[i]==null) 
        continue; 
       SW = new StreamWriter(tc[i].GetStream()); 
       SW.WriteLine(name + ": " + msg); 
       SW.Flush(); 
       SW = null; 
       } catch
        { 
        string g = (string) TalkServ.handleByConnect[tc[i]]; 
        TalkServ.SendSysMsg("** " + g + " ** HAS LEFT US."); 
        TalkServ.handles.Remove(g); 
        TalkServ.handleByConnect.Remove(tc[i]); 
       } 
      } 
     } 
    
     public static void SendSysMsg(string msg) { 
      StreamWriter SW; 
      ArrayList ToRemove = new ArrayList(0); 
      N.Sockets.TcpClient[] tc = new N.Sockets.TcpClient[TalkServ.handles.Count]; 
      TalkServ.handles.Values.CopyTo(tc,0); 
      for(int i=0;i<tc.Length;i++) { 
       try { 
       if(msg.Trim()==""||tc[i]==null) 
        continue; 
       SW = new StreamWriter(tc[i].GetStream()); 
       SW.WriteLine(msg); 
       SW.Flush(); 
       SW = null; 
       } catch{    TalkServ.handles.Remove(TalkServ.handleByConnect[tc[i]]); 
        TalkServ.handleByConnect.Remove(tc[i]); 
       } 
      } 
     } 
    }//end of class TalkServ 
    
    class BackForth { 
     N.Sockets.TcpClient client; 
     System.IO.StreamReader SR; 
     System.IO.StreamWriter SW; 
     string handle; 
     
     public BackForth(System.Net.Sockets.TcpClient c) { 
      client = c; 
      Thread t = new Thread(new ThreadStart(init)); 
      t.Start(); 
     } 
     
     private string GetHandle() { 
      SW.WriteLine("What is your handle? "); 
      SW.Flush(); 
      return SR.ReadLine(); 
     } 
     
     private void run() { 
      try { 
      string l = ""; 
      while(true) { 
       l = SR.ReadLine(); 
       TalkServ.SendToAll(handle,l); 
      } 
      } catch(Exception ex) { Console.WriteLine(ex.Message); } 
     } 
     
     private void init() { 
      SR = new System.IO.StreamReader(client.GetStream()); 
      SW = new System.IO.StreamWriter(client.GetStream()); 
      SW.WriteLine("WELCOME TO TalkServ! Be Nice!"); 
      //SW.WriteLine("What is your handle? "); 
      //SW.Flush(); 
      handle = GetHandle(); 
      while(TalkServ.handles.Contains(handle)) { 
       SW.WriteLine("ERR - Handle already exists!"); 
       handle = GetHandle(); 
      } 
      TalkServ.handles.Add(handle,client); 
      TalkServ.handleByConnect.Add(client,handle); 
      TalkServ.SendSysMsg("** " + handle + " ** HAS JOINED US."); 
      SW.WriteLine("Now Talking.....\r\n-------------------------------"); 
      SW.Flush(); 
      Thread t = new Thread(new ThreadStart(run)); 
      t.Start(); 
     } 
    }

    • Proposed as answer by Neddy Ren Tuesday, February 22, 2011 1:57 AM
    • Marked as answer by Neddy Ren Wednesday, February 23, 2011 3:36 AM
    Friday, February 18, 2011 2:39 PM