1. Reglas generales de cliente y servidor
En el proceso general de interacción cliente-servidor, siga las siguientes reglas
: 1. Uno (servidor) a muchos (clientes)
2. El cliente está activo, el servidor es pasivo
3. El servidor mantiene una operación estable a largo plazo
4. El cliente y No hay interacción directa entre clientes
2. Un ejemplo simple
Las API relacionadas con TCP están bajo System.Net.Sockets. Generalmente, se usa la clase Socket, y las clases TcpListener y TcpClient también se pueden usar directamente. Aquí, se usa la clase Socket.
servidor
class Program
{
const string ip = "127.0.0.1";
const int port = 10002;
static void Main(string[] args)
{
// 建立服务器
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
EndPoint point = new IPEndPoint(IPAddress.Parse(ip), port);
socket.Bind(point);
socket.Listen(100);
Console.WriteLine("服务器启动,等待连接...");
// 监听客户端发起连接
Socket conn = socket.Accept();
Console.WriteLine("有客户端连接...");
// 接收数据
byte[] bytes = new byte[1024];
int len = conn.Receive(bytes);
string inputMsg = Encoding.UTF8.GetString(bytes, 0, len);
Console.WriteLine("<<: " + inputMsg);
// 发送数据
string outputMsg = "Welcome";
conn.Send(Encoding.UTF8.GetBytes(outputMsg));
Console.WriteLine(">>: " + outputMsg);
// 关闭连接
conn.Close();
}
}
cliente
class Program
{
const string ip = "127.0.0.1";
const int port = 10002;
static void Main(string[] args)
{
// 连接至服务器
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
EndPoint point = new IPEndPoint(IPAddress.Parse(ip), port);
socket.Connect(point);
Console.WriteLine("客户端启动,连接到服务器...");
// 发送数据
string outputMsg = "Hello";
socket.Send(Encoding.UTF8.GetBytes(outputMsg));
Console.WriteLine(">>: " + outputMsg);
// 接收数据
byte[] bytes = new byte[1024];
int len = socket.Receive(bytes);
string inputMsg = Encoding.UTF8.GetString(bytes, 0, len);
Console.WriteLine("<<: " + inputMsg);
// 关闭连接
socket.Close();
}
}