[C#] Broadcast a message.
Alright, i got bored and created a console chat server type thing, it is receiving the data from clients but will not broadcast it to the other connected clients. Could someone possibly help?
Server is coded in C#
MessageManager.cs
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace SERVER.Managers
{
class MessageManager
{
private Socket MySocket;
private int MyID;
private AsyncCallback pfnWorkerCallBack;
public static Boolean IsConnected;
private String MyName;
private byte[] dataBuffer = new byte[255];
public MessageManager(Socket MySocket, int MyID, String MyName)
{
this.MySocket = MySocket;
this.MyID = MyID;
this.MyName = MyName;
createMessage("##############################################################################\r\n");
createMessage("Welcome to localhost (127.0.0.1) Port (8000)\r\n");
createMessage("Server Administrator: you@notgetting.lol\r\n");
createMessage("##############################################################################\r\n");
WaitForData();
}
#region "Socket Msg Management"
private void WaitForData()
{
if (pfnWorkerCallBack == null)
{
if (MySocket.Connected == true)
{
pfnWorkerCallBack += new AsyncCallback(DataRecieved);
}
}
if (MySocket.Connected == true)
{
MySocket.BeginReceive(dataBuffer, 0, dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, null);
}
else
{
DropConnection();
}
}
private void DataRecieved(IAsyncResult syncc)
{
try
{
int iRx = 0;
iRx = MySocket.EndReceive(syncc);
if (iRx == 0)
{
DropConnection();
}
char[] chars = new char[iRx];
System.Text.Decoder d = System.Text.Encoding.Default.GetDecoder();
int charLen = d.GetChars(dataBuffer, 0, iRx, chars, 0);
System.String szData = new System.String(chars);
if (szData == Convert.ToChar(10).ToString() + Convert.ToChar(13).ToString())
{
DropConnection();
}
if (szData.Length == 0)
{
WaitForData();
}
if (szData.Length >= 1)
{
if (szData.ToString() != "PONG")
{
String NewData = this.MyName + ": " + szData + "\r\n";
Console.Write(NewData);
BroadCastMsg(NewData, this.MyID);
}
WaitForData();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
internal void BroadCastMsg()
{
//Not sure what to do D:
}
internal void createMessage(String TheData)
{
try
{
byte[] ByeData = Encoding.Default.GetBytes(TheData);
MySocket.Send(ByeData);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.Beep();
}
}
internal void DropConnection()
{
if (IsConnected == true)
{
Console.WriteLine(" Dropped: " + MyName + "\r\n");
MySocket.Close(5);
IsConnected = false;
try
{
Managers.SocketManager.activeSockets.Remove(MyID);
}
catch (Exception ex)
{
Console.WriteLine(" " + ex.Message + " \r\n");
}
}
}
#endregion
}
}
Re: [C#] Broadcast a message.
Please use the C# tag next time in your topic title.