【发布时间】:2021-12-04 01:30:05
【问题描述】:
我必须让多个客户端与服务器通信,服务器选择回复谁。就好像客户端发送消息的唯一目的地是服务器。 服务器选择与谁交谈。
关键是我不知道如何首先创建多个客户端并将消息定向到我想要的任何客户端。
我只需要做一对一的客户端和服务器。
我也不知道我是否必须使用很多线程,因为我需要一个线程来监听新客户端的所有连接,另一个线程来监听他们发送给我的内容,从而能够发送。
我留下我的代码。
对不起我的英语。使用谷歌翻译。
西班牙语: Tengo que hacer que varios clientes se comuniquen con el servidor, y el servidor elige a quién responder。 Es como si el único destino del cliente para enviar el mensaje fuera el servidor。 Y el servidor elige con quién hablar。
El punto es que no sé cómo hacer varios clientes primeo y dirigir los mensajes a cualquiera de esos clientes que quiero。
Solo tengo que hacer un 1 a 1. Cliente y servidor。
Además no sé si tenré que usar muchos hilos, ya que necesitaría un hilo para escuchar todas las conexiones de los nuevos clientes, otro hilo para escuchar lo que me envían y así poder enviar。
Ahí les dejo mi código.
服务器/服务器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Servidor_Chat
{
class Server
{
IPAddress ipAddr;
IPEndPoint endPoint;
Socket s_Server;
Socket s_Client;
public Server()
{
ipAddr = IPAddress.Any;
endPoint = new IPEndPoint(ipAddr, 1234);
s_Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s_Server.Bind(endPoint);
s_Server.Listen(1);
}
public void Start()
{
Console.WriteLine("Esperando clientes...");
s_Client = s_Server.Accept();
Console.WriteLine("Un cliente se ha conectado.");
IPEndPoint clientep = (IPEndPoint)s_Client.RemoteEndPoint;
Console.WriteLine("Conectado con {0} en el puerto {1}", clientep.Address, clientep.Port);
}
public void Send(string msg)
{
string texto = "";
byte[] textoAEnviar;
texto = msg;
textoAEnviar = Encoding.Default.GetBytes(texto);
s_Client.Send(textoAEnviar, 0, textoAEnviar.Length, 0);
}
public void Receive()
{
while (true)
{
Thread.Sleep(500);
byte[] ByRec;
string textoRecibido = "";
ByRec = new byte[255];
int a = s_Client.Receive(ByRec, 0, ByRec.Length, 0);
Array.Resize(ref ByRec, a);
textoRecibido = Encoding.Default.GetString(ByRec);
Console.WriteLine("Client: " + textoRecibido);
Console.Out.Flush();
}
}
}
class Program
{
static void Main(string[] args)
{
Thread t;
Server s = new Server();
s.Start();
t = new Thread(new ThreadStart(s.Receive));
t.Start();
while (true)
{
s.Send(Console.ReadLine());
}
Console.WriteLine("Presione cualquier tecla para terminar");
Console.ReadLine();
}
}
}
客户
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace Cliente_Chat
{
class Program
{
class Client
{
IPAddress ipAddr;
IPEndPoint endPoint;
Socket s_Client;
public Client()
{
ipAddr = IPAddress.Parse("127.0.0.1");
endPoint = new IPEndPoint(ipAddr, 1234);
s_Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void Start()
{
try
{
s_Client.Connect(endPoint);
Console.WriteLine("Conectado con exito");
}
catch (SocketException e)
{
Console.WriteLine("No se pudo conectar al servidor");
Console.WriteLine(e.ToString());
return;
}
}
public void Send(string msg)
{
string texto = "";
byte[] textoAEnviar;
texto = msg;
textoAEnviar = Encoding.Default.GetBytes(texto);
s_Client.Send(textoAEnviar, 0, textoAEnviar.Length, 0);
}
public void Receive()
{
while (true)
{
Thread.Sleep(500);
byte[] ByRec;
string textoRecibido = "";
ByRec = new byte[255];
int a = s_Client.Receive(ByRec, 0, ByRec.Length, 0);
Array.Resize(ref ByRec, a);
textoRecibido = Encoding.Default.GetString(ByRec);
Console.WriteLine("Server: " + textoRecibido);
Console.Out.Flush();
}
}
}
static void Main(string[] args)
{
Thread t;
Client c = new Client();
c.Start();
t = new Thread(new ThreadStart(c.Receive));
t.Start();
while (true)
{
c.Send(Console.ReadLine());
}
Console.WriteLine("Presione cualquier tecla para terminar");
Console.ReadLine();
}
}
}
【问题讨论】:
-
您将能够在网络中找到多个客户端服务器应用程序示例。
-
根据您的要求,有多个库和包可以用最少的低级代码完成您正在做的事情。如果您将 IIS 用于服务器,您可以将 SignalR 用于服务器和客户端,只关注您的业务规则。图书馆会处理剩下的。
-
如果你不能使用 IIS 或者不想要 websockets,你可以使用github.com/chronoxor/NetCoreServer。它支持客户端和服务器,并在后台执行所有线程,因此您可以专注于业务逻辑。
标签: c# sockets client-server tcpclient tcplistener