如何在 C# 中实现套接字(How to implement sockets in C#)

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

套接字 是一种通信通道,用于帮助不同的系统相互通信。 套接字编程是一种开发程序的方法,它允许系统通过套接字交换消息。它已在多种语言中实现,包括 C、Java、Ruby 和 JavaScript 等。

套接字编程分为客户端和服务端两个部分。

服务器端

服务器是满足客户端请求的系统。它为客户端提供资源,并通过发送和接收消息确保多个客户端之间的通信。

我们可以使用以下方法在服务器上实现套接字。

using System;

using System.Net;

using System.Net.Sockets;

using System.Text;

导入库

  • 我们导入了所有必要的命名空间。

public class Server { public static void Main() {

创建带有 Main 方法的 Server 类

  • 我们创建Server类并Main在其中声明一个执行代码的方法。

IPAddress serverAddress = IPAddress.Parse("12.0.0.7");

int serverPort = 8000;

定义我们服务器的 IP 地址和端口号

  • 我们会存储服务器使用的 IP 地址和端口号。

Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

创建套接字

  • 我们使用 socket 类创建套接字。该类中的参数AddressFamily.InterNetwork指定套接字使用 IPv4 地址,SocketType.StreamProtocolType.cp指定连接类型为 TCP。

serverSocket.Bind(new IPEndPoint(serverAddress, serverPort));

将服务器的 IP 地址和端口号绑定到服务器

  • 我们使用该函数将我们的套接字与服务器的 IP 地址和端口连接起来Bind

serverSocket.Listen(5);

激活服务器并使其准备就绪

  • Listen方法使服务器处于活动状态并准备好接受客户端连接。函数中的参数表示服务器serverSocket在开始拒绝新连接之前可以排队等待的最大连接数。

Socket clientSocket = serverSocket.Accept();

接受客户的请求

  • 我们调用该函数Accept来接受传入的客户端连接。该函数返回客户端和服务器之间已连接的共享套接字,并将其存储在变量中clientSocket

byte\[\] temp = new byte1024;

int clientBytes = clientSocket.Receive(temp);

string clientMessage = Encoding.ASCII.GetString(temp, 0, clientBytes);

收到来自客户端的消息

  • 我们创建一个字节数组temp来存储客户端发送的字节。该函数Receive接收客户端发送的消息。接收到的消息是字节格式的,因此将其转换为字符串并存储在变量中clientMessage

string serverMessage = "Hello, client!";

byte\[\] temp2 = Encoding.ASCII.GetBytes(serverMessage);

clientSocket.Send(temp2);

向客户发送消息

  • 该字符串serverMessage包含服务器要发送给客户端的消息。它会被转换为字节格式并存储在字节数组中temp2。该Send函数会将消息以字节格式发送给客户端。

clientSocket.Shutdown(SocketShutdown.Both);

clientSocket.Close();

serverSocket.Close();

关闭连接

  • 最后一步,我们使用ShutdownandClose方法断开客户端与服务器之间的连接,然后分别关闭客户端和服务器的套接字。

客户端

客户端向服务器发送请求以使用其服务。客户端和服务器建立连接后,即可交换消息和数据。

我们可以通过以下步骤在客户端实现套接字。

using System;

using System.Net;

using System.Net.Sockets;

using System.Text;

导入库

  • 我们导入了所有必要的命名空间。

public class Client { public static void Main() {

创建客户端类和主方法

  • 我们创建Client类并Main在其中声明一个执行代码的方法。

IPAddress serverAddress = IPAddress.Parse("12.0.0.7");

int serverPort = 8000;

定义服务器的 IP 地址和端口号

  • 我们会存储服务器使用的 IP 地址和端口号。我们将使用这些信息向该特定服务器发送请求。

Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

创建套接字

  • 我们使用 socket 类创建套接字。该类中的参数AddressFamily.InterNetwork指定套接字使用 IPv4 地址,SocketType.StreamProtocolType.cp指定连接类型为 TCP。

clientSocket.Connect(new IPEndPoint(serverIP, serverPort));

使用服务器的 IP 地址和端口号连接客户端

  • 我们使用该函数向服务器发送连接请求Connect。我们将服务器的端口号和 IP 地址作为参数发送。

string clientMessage = "Hello, server!";

byte\[\] temp = Encoding.ASCII.GetBytes(clientMessage);

clientSocket.Send(temp);

向服务器发送消息

  • 该字符串clientMessage包含我们发送给服务器的消息。它会被转换为字节格式并存储在字节数组中temp。该函数Send会将消息以字节格式发送给客户端。

byte\[\] temp2 = new byte1024;

int serverBytes = clientSocket.Receive(temp2);

string serverMessage = Encoding.ASCII.GetString(temp2, 0, serverBytes);

正在接收来自服务器的消息

  • 我们创建一个字节数组temp2来存储服务器发送的字节。我们使用该Receive函数读取客户端的消息。接收到的消息是字节格式的,因此将其转换为字符串并存储在变量中serverMessage

clientSocket.Shutdown(SocketShutdown.Both);

clientSocket.Close();

关闭连接

  • 最后一步,我们使用ShutdownandClose方法分别断开客户端与服务器之间的连接,然后关闭客户端的套接字。

完整示例

以下代码示例展示了在学习到的客户端-服务器模型的工作原理。

Server

using System;

using System.Net;

using System.Net.Sockets;

using System.Text;

public class Server

{

public static void Main()

{

// Setting up the server IP address and port number

IPAddress serverAddress = IPAddress.Parse("127.0.0.7");

int serverPort = 8000;

// Creating our server socket

Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

// Binding the socket

serverSocket.Bind(new IPEndPoint(serverAddress, serverPort));

// server listening for incoming connections

serverSocket.Listen(5);

Console.WriteLine("Server is listening for connections");

while(true)

{

// Accepting a client connection

Socket clientSocket = serverSocket.Accept();

Console.WriteLine("Client connected!");

// Receiving message from the client

byte\[\] temp = new byte1024;

int clientBytes = clientSocket.Receive(temp);

string clientMessage = Encoding.ASCII.GetString(temp, 0, clientBytes);

Console.WriteLine("Received data from client: " + clientMessage);

// Process and perform operations on the received data

// Sending the message back to the client

string serverMessage = "Hello, client!";

byte\[\] temp2 = Encoding.ASCII.GetBytes(serverMessage);

clientSocket.Send(temp2);

// Closing the connection

clientSocket.Shutdown(SocketShutdown.Both);

clientSocket.Close();

}

// Close the server socket

serverSocket.Close();

}

}

Client

using System;

using System.Net;

using System.Net.Sockets;

using System.Text;

public class Client

{

public static void Main()

{

// Setting up the server IP address and port number

IPAddress serverAddress = IPAddress.Parse("127.0.0.7");

int serverPort = 8000;

// Creating our client socket

Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

// Connecting to the server

clientSocket.Connect(new IPEndPoint(serverAddress,serverPort));

Console.WriteLine("Connected to server!");

// Sending message to the server

string clientMessage = "Hello, server!";

byte\[\] temp = Encoding.ASCII.GetBytes(clientMessage);

clientSocket.Send(temp);

// Receiving message from the server

byte\[\] temp2 = new byte1024;

int serverBytes = clientSocket.Receive(temp2);

string serverMessage = Encoding.ASCII.GetString(temp2, 0, serverBytes);

Console.WriteLine("Received response from server: " + serverMessage);

// Closing the connection

clientSocket.Shutdown(SocketShutdown.Both);

clientSocket.Close();

}

}

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。