Сокеты. Отправка сообщений всем клиентам или только одному - C#
Формулировка задачи:
Здравствуйте, имеется вот такой сервер на C#:
Суть вопроса: Как мне отправлять какое то всем клиентам одновременно, а другое сообщение определённому клиенту.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleServer
{
public struct client_attr
{
public int count;
public string ip;
public string name;
}
public struct connections
{
public string firstClient;
public string secondClient;
public string[] msg;
}
class Program
{
public static string data = null;
public static bool exit = false;
static int count = 0;
static bool spisok = false;
static string[] clients = new string[10];
static String host = System.Net.Dns.GetHostName();
public static void start_server()
{
try
{
System.Net.IPAddress ip = System.Net.Dns.GetHostByName(host).AddressList[0];
IPAddress localAddress = IPAddress.Parse(ip.ToString());
IPEndPoint ipEndpoint = new IPEndPoint(localAddress, 65);
Socket sListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sListener.Bind(ipEndpoint);
sListener.Listen(1);
while (true)
{
//Invoke(new AddMessageDelegate(LogAdd), new object[] { "Ожидаем соединение. " + ip.ToString() + ":65" + "\n" });
Console.WriteLine("Ожидаем соединение. " + ip.ToString() + ":65");
Socket handler = sListener.Accept();
Thread Thread2 = new Thread(delegate() { obs(handler); });
Thread2.Start();
if (exit == true)
{
handler.Shutdown(SocketShutdown.Both);
handler.Close();
Thread2.Abort();
break;
}
}
}
catch (Exception ex)
{
// Invoke(new AddMessageDelegate(LogAdd), new object[] { ex.ToString() + "\n" });
Console.WriteLine(ex.ToString());
}
}
static void reciv(Socket handler)
{
try
{
byte[] bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data = Encoding.UTF8.GetString(bytes, 0, bytesRec);
}
catch
{
// Invoke(new AddMessageDelegate(LogAdd), new object[] { "Соединение прервано" });
Console.WriteLine("Соединение прервано");
}
}
static void obs(Socket handler)
{
client_attr[] client1 = new client_attr[30];
count += 1;
clients[count] = ((IPEndPoint)handler.RemoteEndPoint).Address.ToString();
while (true)
{
Thread thread3 = new Thread(delegate() { reciv(handler); });
thread3.Start();
//Invoke(new AddMessageDelegate(LogAdd), new object[] { count + "\n" });
//Invoke(new AddMessageDelegate(LogAdd), new object[] { data + "\n" });
//Console.WriteLine(count);
// Console.WriteLine(data);
if (data == "exit")
{
//Invoke(new Action(() => { listBox1.Items.RemoveAt(client1[count].count); }));
client1[count].count = -1;
client1[count].ip = null;
client1[count].name = null;
handler.Shutdown(SocketShutdown.Both);
handler.Close();
// Invoke(new AddMessageDelegate(LogAdd), new object[] { "Соединение завершено\n" });
Console.WriteLine("Соединение завершено");
Console.WriteLine("disconnect" + ":" + client1[count].name + "::" + count);
break;
}
else if (client1[count].name == null)
{
client1[count].ip = ((IPEndPoint)handler.RemoteEndPoint).Address.ToString();
client1[count].name = data;
client1[count].count = count;
//byte [] list_mem = new byte[listBox1.Items.Count];
handler.Send(Encoding.UTF8.GetBytes(client1[count].name+""));
// handler.Send(Encoding.UTF8.GetBytes();
// Invoke(new Action(() => { listBox1.Items.Add(client1[count].name); }));
// Invoke(new AddMessageDelegate(LogAdd), new object[] { "Клиент " + client1[count].name + " с IP: " + client1[count].ip + " подключился.\n" });
Console.WriteLine("Клиент " + client1[count].name + " с IP: " + client1[count].ip + " подключился.");
}
else if (client1[count].name != null)
{
for (int i = 1; i < count+1; i++)
{
// if (client1[0].name != client1[count].name)
// {
if (spisok == false)
{
handler.Send(Encoding.UTF8.GetBytes(i+":"+client1[i].name));
spisok = true;
// Invoke(new AddMessageDelegate(LogAdd), new object[] { client1[count].name });
//Console.WriteLine(client1[count].name);
// }
}
}
}
else if (data.IndexOf("connect") >= 0)
{
connections[] connect = new connections[1];
int start = data.IndexOf(":");
int end = data.IndexOf("::");
int len = end - start;
connect[0].firstClient = data.Substring(start, len);
start = data.IndexOf("::");
end = data.IndexOf(":::");
len = end - start;
connect[0].secondClient = data.Substring(start, len);
// Invoke(new AddMessageDelegate(LogAdd), new object[] { connect[0].firstClient + "" + connect[0].secondClient });
Console.WriteLine(connect[0].firstClient + "" + connect[0].secondClient);
}
Thread.Sleep(500);
}
}
static void Main(string[] args)
{
start_server();
}
Как мне отправить список подключенных к серверу клиентов, всем клиентам?
Решение задачи: «Сокеты. Отправка сообщений всем клиентам или только одному»
textual
Листинг программы
clientSocket.Add(handler);