This code snippet demonstrates how to broadcast messages to all connected clients. The server listens for incoming connections. Each connection is handled by a new thread. The server maintains a list of all connected clients in an array. When a client sends a message to the server, the thread responsible for that client then sends the message to all clients except for it's self. Run the server first then load multiple client instances.
Client
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Threading;
namespace Client
{
class Program
{
static void Main(string[] args)
{
try
{
TcpClient tcpClient = new TcpClient("127.0.0.1", 1234);
Console.WriteLine("Connected to server.");
Console.WriteLine("");
Thread thread = new Thread(Read);
thread.Start(tcpClient);
StreamWriter sWriter = new StreamWriter(tcpClient.GetStream());
while (true)
{
if (tcpClient.Connected)
{
string input = Console.ReadLine();
sWriter.WriteLine(input);
sWriter.Flush();
}
}
}
catch (Exception e)
{
Console.Write(e.Message);
}
Console.ReadKey();
}
static void Read(object obj)
{
TcpClient tcpClient = (TcpClient)obj;
StreamReader sReader = new StreamReader(tcpClient.GetStream());
while (true)
{
try
{
string message = sReader.ReadLine();
Console.WriteLine(message);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
break;
}
}
}
}
}
Server
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Threading;
namespace Server
{
class Program
{
private static TcpListener tcpListener;
private static List<TcpClient> tcpClientsList = new List<TcpClient>();
static void Main(string[] args)
{
tcpListener = new TcpListener(IPAddress.Any, 1234);
tcpListener.Start();
Console.WriteLine("Server started");
while (true)
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
tcpClientsList.Add(tcpClient);
Thread thread = new Thread(ClientListener);
thread.Start(tcpClient);
}
}
public static void ClientListener(object obj)
{
TcpClient tcpClient = (TcpClient)obj;
StreamReader reader = new StreamReader(tcpClient.GetStream());
Console.WriteLine("Client connected");
while (true)
{
string message = reader.ReadLine();
BroadCast(message, tcpClient);
Console.WriteLine(message);
}
}
public static void BroadCast(string msg, TcpClient excludeClient)
{
foreach (TcpClient client in tcpClientsList)
{
if (client != excludeClient)
{
StreamWriter sWriter = new StreamWriter(client.GetStream());
sWriter.WriteLine(msg);
sWriter.Flush();
}
}
}
}
}
2 comments:
Thank you very much! This is what I want! I so appreciate it!
Nice article!!
Have a look Bulk sms services
Post a Comment