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.