在ASP.NET中,使用Socket进行点对点(P2P)传输需要创建一个TCP客户端和服务器。以下是一个简单的示例,展示了如何在ASP.NET中使用Socket实现点对点传输。
首先,创建一个TCP服务器:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class TcpServer
{
private const int Port = 5000;
public static void Main(string[] args)
{
TcpListener server = null;
try
{
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, Port);
Console.WriteLine("Server started...");
server.Start();
while (true)
{
Console.Write("Waiting for connection ... ");
Socket handler = server.AcceptSocket();
Console.WriteLine("Connected!");
Task.Run(() => HandleClient(handler));
}
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
server?.Stop();
}
}
private static async Task HandleClient(Socket handler)
{
byte[] buffer = new byte[1024 * 1024];
int bytesRead;
while ((bytesRead = await handler.ReceiveAsync(new ArraySegment<byte>(buffer), SocketFlags.None)) != 0)
{
string data = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received: " + data);
string response = "Message received!";
byte[] responseBytes = Encoding.UTF8.GetBytes(response);
await handler.SendAsync(new ArraySegment<byte>(responseBytes), SocketFlags.None);
}
Console.WriteLine("Disconnected!");
handler.Close();
}
}
接下来,创建一个TCP客户端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class TcpClient
{
private const string ServerIp = "127.0.0.1";
private const int ServerPort = 5000;
public static async Task Main(string[] args)
{
TcpClient client = new TcpClient();
try
{
await client.ConnectAsync(ServerIp, ServerPort);
string message = "Hello, Server!";
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(messageBytes), SocketFlags.None);
byte[] buffer = new byte[1024 * 1024];
int bytesRead = await client.ReceiveAsync(new ArraySegment<byte>(buffer), SocketFlags.None);
string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("Server response: " + response);
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
client.Close();
}
}
}
在这个示例中,我们创建了一个TCP服务器和一个TCP客户端。服务器监听端口5000,等待客户端连接。当客户端连接到服务器时,它们会相互发送消息。
要运行此示例,请将TCP服务器代码放在一个名为TcpServer.cs
的文件中,将TCP客户端代码放在一个名为TcpClient.cs
的文件中。然后,分别编译并运行这两个文件。首先启动服务器,然后启动客户端。你应该会在服务器和客户端的控制台上看到它们相互发送的消息。