Member Avatar for FakeTales

Hey i have a basic game which requires a client to guess the number which is located on the server side, mutliple clients can access the same game. The client sends their guess this in turn passes to a middleware server then this then goes to the end server. If the client guesses the number correct they are informaed , however i would like the message "we have a winner" broadcasted to all the clients connected to the server.

Client side 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.Text.RegularExpressions;


namespace client
{
    public partial class Form1 : Form
    {
        private byte[] data = new byte[1024];
        private Socket client;

        int guessCount = 0;


        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            lblGuessCount.Text = guessCount.ToString();
        }

        #region Client Load

        private void Form1_Load(object sender, EventArgs e)
        {
            gbClientInput.Enabled = false;
            gbClientReg.Enabled = false;
            gbClientInput.Visible = false;
            gbClientReg.Visible = false;
        }

        #endregion

        #region Client Button Connect

        private void btnConnect_Click(object sender, EventArgs e)
        {
            gbClientReg.Visible = true;
            gbClientReg.Enabled = true;
            gbClientInput.Enabled = true;
            gbClientInput.Visible = true;

            try
            {

            btnConnect.Enabled = false;
            btnQuit.Enabled = true;
            btnReg.Enabled = true;
            btnSend.Enabled = true;
            btnClear.Enabled = false;

            txtSerStat.Text = "Connecting to server .... ";
            client = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            int port;
            port = int.Parse(txtPort.Text);
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(txtIp.Text), port);
            client.BeginConnect(remoteEP, new AsyncCallback(OnConnected), null);  
            }
            catch
            {
                CloseConnection();
            }


        }
        #endregion

        #region On Connected

        void OnConnected(IAsyncResult result)
        {
            try
            {
                client.EndConnect(result);
                txtSerStat.Text = "Connected to = " + client.RemoteEndPoint;
                client.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);
            }
            catch
            {
                CloseConnection();
            }
        }
        #endregion

        #region OnDataReceived 

        void OnDataReceived(IAsyncResult result)
        {
            try
            {
                int receive = client.EndReceive(result);
                string message = Encoding.ASCII.GetString(data, 0, receive);
                txtClientDisplay.Text += message + "\r\n";

                string input = message;

                // Here we call Regex.Match.
                Match match = Regex.Match(input, "Congrats you won!!!");

                // Here we check the Match instance.
                if (match.Success)
                {
                    // Finally, we get the Group value and display it.

                    byte[] messageNew = Encoding.ASCII.GetBytes("We have a winner");
                    client.BeginSend(messageNew, 0, messageNew.Length, SocketFlags.None, new AsyncCallback(OnDataSent), null);


                    DialogResult resultWon = MessageBox.Show("Congrats you have won", "play again?", MessageBoxButtons.YesNo);

                    if (resultWon == DialogResult.Yes)
                    {
                        btnSend.Enabled = true;
                        lblGuessCount.Text = string.Empty;
                        guessCount = 0;
                        lblGuessCount.Text = guessCount.ToString();
                        txtClientDisplay.Text = string.Empty;


                    }

                }
            }
            catch (Exception)
            {
                CloseConnection();
            }
        }

        #endregion

        #region Quit Connection

        private void btnQuit_Click(object sender, EventArgs e)
        {
            CloseConnection();

        }

        #endregion

        #region Close Connection ()

        public void CloseConnection()
        {
            client.Close();
            txtSerStat.Text = "Disconnected";
            btnConnect.Enabled = true;
            btnQuit.Enabled = false;
            btnSend.Enabled = false;
            gbClientInput.Enabled = false;
            gbClientReg.Enabled = false;
            gbClientInput.Visible = false;
            gbClientReg.Visible = false;
        }

        #endregion

        #region Send Guess

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (txtNumber.Text == "")
                {

                  string.IsNullOrWhiteSpace(txtNumber.Text);
                  MessageBox.Show("You havent entered a number");
                  guessCount--;
                  lblGuessCount.Text = guessCount.ToString();

                }
            try
            {
                byte[] message = Encoding.ASCII.GetBytes(txtNumber.Text);
                client.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(OnDataSent), null);
                txtNumber.Text = string.Empty;
                guessCount++;
                lblGuessCount.Text = guessCount.ToString();



                if (guessCount == 10)
                {
                    DialogResult result1 = MessageBox.Show("You have reached the maximum guess count, would you like to play again?", "Guess Count Reached", MessageBoxButtons.YesNo);
                    btnSend.Enabled = false;

                    if (result1 == DialogResult.Yes)
                    {
                        btnSend.Enabled = true;
                        lblGuessCount.Text = string.Empty;
                        guessCount = 0;
                        lblGuessCount.Text = guessCount.ToString(); 
                        txtClientDisplay.Text = string.Empty;
                    }
                    if (result1 == DialogResult.No)
                    {
                        for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
                        {

                                Application.OpenForms[i].Close();
                        }
                    }
                }
                }


            catch
            {
                CloseConnection();
            }

        }

        #endregion

        #region OnDataSent

        void OnDataSent(IAsyncResult result)
        {
            try
            {
                int sent = client.EndSend(result);
                client.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);

            }
            catch
            {
                CloseConnection();
            }

        }
        #endregion

Middleware 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;

namespace middleware
{
    public partial class Form1 : Form
    {
        private Socket server;

        private byte[] clientData = new byte[1024];
        private byte[] datars = new byte[1024];

        private int connections = 0;

        private Socket RemoteClient;
        private Socket ClientReturn;


        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        #region Connect

        private void btnClientStart_Click(object sender, EventArgs e)
        {
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            int port1;
            port1 = int.Parse(txtClientPort.Text);
            IPEndPoint localEP = new IPEndPoint(0, port1);
            server.Bind(localEP);
            server.Listen(4);

            server.BeginAccept(new AsyncCallback(OnConnected), null);

            btnClientStart.Enabled = false;
            txtclientSerStat.Text = "Waiting for client ";
        }

        #endregion

        #region OnConnected

        void OnConnected(IAsyncResult result)
        {
            Socket client = server.EndAccept(result);
            connections++;
            server.BeginAccept(new AsyncCallback(OnConnected), null);

            try
            {
                txtclientSerStat.Text = "" + connections;
                byte[] message = Encoding.ASCII.GetBytes("Welcome to the server");
                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);
                    client.BeginReceive(clientData, 0, clientData.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), client);
                    RemoteClient.BeginSend(echomessage, 0, echomessage.Length, SocketFlags.None, new AsyncCallback(OnRemoteDataSent), null);
                }
            }
            catch (SocketException)
            {
            }
        }

        #endregion

        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();
            }
        }

        void OnConnectedRemote(IAsyncResult result)
        {
            try
            {
                RemoteClient.EndConnect(result);
            }
            catch
            {
                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();
            }

        }

        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);
                ClientReturn.BeginSend(datars, 0, datars.Length, SocketFlags.None, new AsyncCallback(OnDataSentBack), ClientReturn);
            }
            catch (Exception)
            {
                CloseConnection();
            }
        }

        void OnDataSentBack(IAsyncResult result)
        {
            Socket client = (Socket)result.AsyncState;
            try
            {
                int sent = client.EndSend(result);

            }
            catch (SocketException)
            {



            }
        }
    }
}

Finally Server 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;

namespace server
{
    public partial class Server1 : Form
    {
        private Socket server;
        private Socket client;

        private byte[] data = new byte[1024];
        private byte[] dataNew = new byte[1024];


        public Server1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        #region Server Start

        private void btnStartServer_Click(object sender, EventArgs e)
        {
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            int port;
            port = int.Parse(txtServerPort.Text);
            IPEndPoint localEP = new IPEndPoint(0, port);
            server.Bind(localEP);
            server.Listen(0);

           server.BeginAccept(new AsyncCallback(OnConnected), null);
           btnStartServer.Enabled = false;
           txtServerStatus.Text = "Waiting for Middleware";
        }

        #endregion 

        #region OnConnected 

        void OnConnected(IAsyncResult result)
        {
            try
            {
                client = server.EndAccept(result);
                txtServerStatus.Text = "Connected to: " + client.RemoteEndPoint;

                client.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);

            }
            catch (SocketException)
            {
                CloseClient();
            }

        }

        #endregion

        #region OnDataReceived

        void OnDataReceived(IAsyncResult result)
        {

            try
            {

                int receive = client.EndReceive(result);


                string message = Encoding.ASCII.GetString(data, 0, receive);
                txtServerChat.Text += "\r\n" + message;
                txtClientNumber.Text = message;


                Double x;

                if (Double.TryParse(message, out x))
                {

                    int numGen = Convert.ToInt32(txtNumGen.Text);
                    int clientGuess = Convert.ToInt32(message);


                    if (clientGuess == numGen)
                    {
                        string messageWon = message;
                        messageWon = "Congrats you won!!!";
                        byte[] echomessageWon = Encoding.ASCII.GetBytes("You Guessed: " + message + "\r\n" + "Server Says: " + messageWon + "\r\n");
                        client.BeginSend(echomessageWon, 0, echomessageWon.Length, SocketFlags.None, new AsyncCallback(OnDataSent), null);
                    }
                    else if (clientGuess < numGen)
                    {
                        string messageLow = message;
                        messageLow = "Number too low , try again!!!";
                        byte[] echomessageLow = Encoding.ASCII.GetBytes("You Guessed: " + message + "\r\n" + "Server Says: " + messageLow + "\r\n");
                        client.BeginSend(echomessageLow, 0, echomessageLow.Length, SocketFlags.None, new AsyncCallback(OnDataSent), null);
                    }
                    else if (clientGuess > numGen)
                    {
                        string messageHigh = message;
                        messageHigh = "Number too High , try again!!!";
                        byte[] echomessageHigh = Encoding.ASCII.GetBytes("You Guessed: " + message + "\r\n" + "Server Says: " + messageHigh + "\r\n");
                        client.BeginSend(echomessageHigh, 0, echomessageHigh.Length, SocketFlags.None, new AsyncCallback(OnDataSent), null);
                    }
                } 
                    else
                    {
                        string messageNew = message;
                        byte[] echomessage = Encoding.ASCII.GetBytes(messageNew);
                        client.BeginSend(echomessage, 0, echomessage.Length, SocketFlags.None, new AsyncCallback(OnDataSent), null);

                    }
                }



            catch (SocketException)
            {

            }

        }

        #endregion

        void OnDataSent(IAsyncResult result)
        {
            try
            {
                int sent = client.EndSend(result);
                client.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);
            }
            catch (SocketException)
            {

            }
        }



        public void CloseClient()
        {
            client.Close();
            btnStartServer.Enabled = true;
            txtServerStatus.Text = "Disconnected";
        }

        private void txtClientNumber_TextChanged(object sender, EventArgs e)
        {

        }
    }
}

So to recap on the server side there is a number (at the moment it is hard coded), multiple clients can connect to the middleware server which is then connected to an end server. The client can then start guessing the number, if they are correct i can send a message back to an individual client who made the correct guess , however i would like to broadcast this message to all connected clients to inform them that basically someone has guessed the number correctly so it is game over. i cant figure out how to broadcast a single "we have a winner" message to all connected clients.

Recommended Answers

All 6 Replies

You'll need to make a collection of the clients then loop through the collection and send your message.

Member Avatar for FakeTales

would it be ideal to keep the connected clients list within the middleware ? and then pass that list on to the server? i assumed i would need a connected client list, however all the clients connect via the same port so how would the server know which clients to send the messages to? assign an Id to the clients? i am pretty new to c#

Member Avatar for FakeTales

i have managed now to create a connected client list within the middleware however i cant get a for loop to work to broadcast to all client. i will add the new snippets of code and my attempt on the for loop. This is all on the middleware.All the new code has been marked with the //NEW.

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
      //NEW  private System.Collections.ArrayList SocketList =
       //NEW     ArrayList.Synchronized(new System.Collections.ArrayList());


      //NEW  public delegate void UpdateClientListCallback();

        private Socket RemoteClient;
        private Socket ClientReturn;

        #endregion




 void OnConnected(IAsyncResult result)
        {
            try
            {

            //end the accept call 
            Socket client = server.EndAccept(result);

            //increment the client count 
            //NEW Interlocked.Increment(ref connections);

            //add the socket to the array list 
            SocketList.Add(client);

            // update the rich text box showing our connected clients 
           //NEW UpdateClientListControler();

            server.BeginAccept(new AsyncCallback(OnConnected), null);

                txtclientSerStat.Text = "" + connections;
                byte[] message = Encoding.ASCII.GetBytes("Welcome to the server");
                client.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(OnDataSent), client);
            }
            catch (SocketException)
            {
            }
        }



 #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 clientKey = Convert.ToString("client" + i );
                Socket client = (Socket)SocketList[i];
                if (client != null)
                {
                    if (client.Connected)
                    {
                        lstConnectedClients.Items.Add(clientKey);
                    }
                }
            }
        }

        #endregion

And here is the for loop

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);
                ClientReturn.BeginSend(datars, 0, datars.Length, SocketFlags.None, new AsyncCallback(OnDataSentBack), ClientReturn);
                string input = message;

                // Here we call Regex.Match.
                Match match = Regex.Match(input, "we have a winner");

                // Here we check the Match instance.
                if (match.Success)
                {
                    byte[] messageNew = Encoding.ASCII.GetBytes("We have a winner");

                    for (int i = 0; i < SocketList.Count; i++)
                    {

                        ClientReturn.BeginReceive(messageNew, 0, messageNew.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), ClientReturn);
                    }
                }
            }

            catch (Exception)
            {
                CloseConnection();
            }

        }

i have used a regular expression to search the message for a string containing "we have a winner" as this is a basic game if one client wins then all other clients need to be informed of this. I am 100% sure there is a problem with my for loop.

Hi, Would it be possible to receive these project files?

similar to team_1, any chance of having the project files.

email: no.spam@talktalk.net

Cheers.

HI. Do you have the source code?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.