3 Replies - 1840 Views - Last Post: 30 November 2012 - 03:35 PM Rate Topic: -----

#1 FakeTales  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 30-November 12

c# TCP server loop wont broadcast message to all connect clients

Posted 30 November 2012 - 10:36 AM

I have a client , middleware and server . The concept is a client sends a number this passes through the middleware to the server. The server checks the number against the number generated on the server side , if the client guesses the number correctly a message is then passed back to the client , however multiple clients can connect to the server , i have made an array to store the connected clients and tried implementing a for loop to broadcast a message back to the connected clients to inform them that a client has won. However the for loop will only broadcast to one client, the loop is located within the section called:

" void OnRemoteDataReceived(IAsyncResult result)"

heres the code for the middleware


#region using 
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.Net.NetworkInformation;
using System.Collections;
using System.Threading;
using System.Text.RegularExpressions;
        #endregion 
        #region namespace & class
namespace middleware
{
    public partial class Form1 : Form
    {
        private Socket server;
        private byte[] clientData = new byte[1024];
        private byte[] datars = new byte[1024];
        //variable to keep track of connected clients
        private int connections = 0;
        // Array to keep a list of sockets that are assigned to each connected client
        private System.Collections.ArrayList SocketList =
            ArrayList.Synchronized(new System.Collections.ArrayList());
        public delegate void UpdateClientListCallback();
        private Socket RemoteClient;
        private Socket ClientReturn;
        #endregion
        #region form
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        #endregion 
        #region Connect
        private void btnClientStart_Click(object sender, EventArgs e)
        {
            // create listening socket 
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            int port1;
            port1 = int.Parse(txtClientPort.Text);
            IPEndPoint localEP = new IPEndPoint(0, port1);
            // bind to local ip
            server.Bind(localEP);
            // start listening 
            server.Listen(4);
            // call back for clients that are connected
            server.BeginAccept(new AsyncCallback(OnConnected), null);
            //endpoint for clients
            EndPoint epSender = (EndPoint)localEP;
            btnClientStart.Enabled = false;
            txtclientSerStat.Text = "Waiting for client ";
            UpdateControls(true);
        }
        #endregion
        #region UpdateControls
        private void UpdateControls(bool listening)
        {
            btnClientStart.Enabled = !listening;
            btnServerBusy.Enabled = listening;
        }
        #endregion
        #region OnConnected
        // once a client has connected this call back function will be invoked
        void OnConnected(IAsyncResult result)
        {
            try
            {
            //end the accept call 
            Socket client = server.EndAccept(result);
            //increment the client count 
            Interlocked.Increment(ref connections);
            //add the socket to the array list 
            SocketList.Add(client);
            // update the rich text box showing our connected clients 
            UpdateClientListControler();
            // wait for new client connections
            server.BeginAccept(new AsyncCallback(OnConnected), null);
            txtclientSerStat.Text = "" + connections;
            byte[] message = Encoding.ASCII.GetBytes("Welcome to the server client#"  
                + connections);
            //sends welcome message to the client
            client.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(OnDataSent), client);
            }
            catch (SocketException)
            {
            }
        }
        #endregion
        #region OnDataSent
        void OnDataSent(IAsyncResult result)
        {
            Socket client = (Socket)result.AsyncState;
            try
            {
                int sent = client.EndSend(result);
                client.BeginReceive(clientData, 0, clientData.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), client);
            }
            catch (SocketException)
            {
            }
        }
        #endregion
        #region OnDataReceived
        void OnDataReceived(IAsyncResult result)
        {
            Socket client = (Socket)result.AsyncState;
            ClientReturn = (Socket)result.AsyncState;
            try
            {
                int receive = client.EndReceive(result);
                if (receive == 0)
                {
                    return;
                }
                else
                {
                    string message = Encoding.ASCII.GetString(clientData, 0, receive);
                    txtGamedisplay.Text += "\r\n" + message;
                    txtServer1Data.Text = message;
                    byte[] echomessage = Encoding.ASCII.GetBytes(message);
                    RemoteClient.BeginSend(echomessage, 0, echomessage.Length, SocketFlags.None, new AsyncCallback(OnRemoteDataSent), null);
                    client.BeginReceive(clientData, 0, clientData.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), client);
                }
            }
            catch (SocketException)
            {
            }
        }
        #endregion
        #region btnServer1Connect 
        private void btnServer1Connect_Click(object sender, EventArgs e)
        {
            try
            {
                btnServer1Connect.Enabled = false;
                RemoteClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                int port;
                port = int.Parse(txtServer1Port.Text);
                IPEndPoint remoteEPoint = new IPEndPoint(IPAddress.Parse(txtServer1Ip.Text), port);
                RemoteClient.BeginConnect(remoteEPoint, new AsyncCallback(OnConnectedRemote), null);
            }
            catch
            {
                CloseConnection();
            }
        }
        #endregion 
        #region OnConnectedRemote
        void OnConnectedRemote(IAsyncResult result)
        {
            try
            {
                RemoteClient.EndConnect(result);
            }
            catch
            {
                CloseConnection();
            }
        }
        #endregion
        #region CloseConnection 
        public void CloseConnection()
        {
            RemoteClient.Close();
        }
        void OnRemoteDataSent(IAsyncResult result)
        {
            try
            {
                int sent = RemoteClient.EndSend(result);
                RemoteClient.BeginReceive(clientData, 0, clientData.Length, SocketFlags.None, new AsyncCallback(OnRemoteDataReceived), null);
            }
            catch (SocketException)
            {
                CloseConnection();
            }
        }
        #endregion
        #region OnRemoteDataReceived
        void OnRemoteDataReceived(IAsyncResult result)
        {
            try
            {
                int receive = RemoteClient.EndReceive(result);
                string message = Encoding.ASCII.GetString(clientData, 0, receive);
                txtRecServer1.Text = message;
                datars = Encoding.ASCII.GetBytes(txtRecServer1.Text);
                string input = txtRecServer1.Text;
                // Here we call Regex.Match.
                Match match = Regex.Match(input, "We have a winner");
                // Here we check the Match instance.
                if (match.Success)
                {
                    string msg = txtRecServer1.Text;
                    msg = "Server Msg: " + msg + "\n";
                    byte[] byData = System.Text.Encoding.ASCII.GetBytes(msg);
                    Socket client = null;
                        for (int i = 0; i < SocketList.Count; i++)
                        {
                            client = (Socket)SocketList[i];
                             ClientReturn.BeginSend(byData, 0, byData.Length, SocketFlags.None,
                                new AsyncCallback(OnDataSentBack), ClientReturn); 
                        }
                }
                         else
                         {
                            ClientReturn.BeginSend(datars, 0, datars.Length, SocketFlags.None, 
                                new AsyncCallback(OnDataSentBack), ClientReturn);
                         }
                }
            catch (Exception)
            {
                CloseConnection();
            }
        }
        #endregion
        #region OnDataSentBack 
        void OnDataSentBack(IAsyncResult result)
        {
            Socket client = (Socket)result.AsyncState;
            try
            {
                    int sent = client.EndSend(result);
            }
            catch (SocketException)
            {
            }
        }
        #endregion
        #region UpdateClientListControler
        private void UpdateClientListControler()
        {
            if (InvokeRequired)
            {
                lstConnectedClients.BeginInvoke(new UpdateClientListCallback(UpdateClientList), null);
            }
            else
            {
                UpdateClientList();
            }
        }
        #endregion
        #region UpdateClientList 
        void UpdateClientList()
        {
            lstConnectedClients.Items.Clear();
            for (int i = 0; i < SocketList.Count; i++)
            {
                string clientName = Convert.ToString("client ");
                string clientKey = Convert.ToString(i+1 );
                Socket client = (Socket)SocketList[i];
                if (client != null)
                {
                    if (client.Connected)
                    {
                        lstConnectedClients.Items.Add(clientName + clientKey);
                    }
                }
            }
        }
        #endregion
        private void btnServerBusy_Click(object sender, EventArgs e)
        {
        }
    }
}




i have been trying to get the for loop to broadcast the message to all the connected clients for the past couple of hours with no luck, i cant see anything wrong with the for loop

Is This A Good Question/Topic? 0
  • +

Replies To: c# TCP server loop wont broadcast message to all connect clients

#2 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1010
  • View blog
  • Posts: 2,444
  • Joined: 04-October 09

Re: c# TCP server loop wont broadcast message to all connect clients

Posted 30 November 2012 - 01:28 PM

In line 207 you get the client socket, but you never use it.
Was This Post Helpful? 0
  • +
  • -

#3 FakeTales  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 30-November 12

Re: c# TCP server loop wont broadcast message to all connect clients

Posted 30 November 2012 - 02:31 PM

Even if i change the code to this , it still wont work
for (int i = 0; i < SocketList.Count; i++)
   {
 ClientReturn = (Socket)SocketList[i];

  if (ClientReturn.Connected)
    {
       ClientReturn.Send(byData);
    }
}


Was This Post Helpful? 0
  • +
  • -

#4 FakeTales  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 30-November 12

Re: c# TCP server loop wont broadcast message to all connect clients

Posted 30 November 2012 - 03:35 PM

i have solved it , i put the statement on a button click and the data would only be returned after another guess had been clicked , so the client wasn't always openly looking for data. I added some code to the client side to correct this and now it works. If anyone is interested in this i can post the whole lot of code.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1