在ASP.NET中實現Socket通信,你可以使用System.Net.Sockets命名空間中的TcpClient類。以下是一個簡單的示例,展示了如何在ASP.NET應用程序中使用Socket進行通信:
TcpClient實例并連接到遠程服務器:using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class SocketCommunication
{
private const string ServerIp = "127.0.0.1";
private const int ServerPort = 5000;
public async Task SendDataAsync(string message)
{
using (var client = new TcpClient(ServerIp, ServerPort))
{
var networkStream = client.GetStream();
byte[] data = Encoding.UTF8.GetBytes(message);
await networkStream.WriteAsync(data, 0, data.Length);
}
}
}
SocketCommunication類發送數據:using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
private readonly SocketCommunication _socketCommunication;
public MyController(SocketCommunication socketCommunication)
{
_socketCommunication = socketCommunication;
}
[HttpPost("send")]
public async Task<IActionResult> Send([FromBody] string message)
{
await _socketCommunication.SendDataAsync(message);
return Ok();
}
}
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class Server
{
private const int Port = 5000;
public static async Task Main(string[] args)
{
using (var server = new TcpListener(IPAddress.Any, Port))
{
server.Start();
Console.WriteLine("Server started...");
while (true)
{
var client = await server.AcceptTcpClientAsync();
_ = HandleClientAsync(client);
}
}
}
private static async Task HandleClientAsync(TcpClient client)
{
using (var networkStream = client.GetStream())
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = await networkStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Received: {message}");
}
}
}
}
這個示例展示了如何在ASP.NET應用程序中使用Socket進行通信。你可以根據需要修改代碼以滿足你的具體需求。