Created
September 26, 2025 13:41
-
-
Save emeryao/2729a9e4181d25e2564c401d3fa7c6e2 to your computer and use it in GitHub Desktop.
TCP Client in ASP.NET Core Web API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Mvc; | |
using System.Net.Sockets; | |
namespace SimpleSocket.Controllers; | |
[ApiController] | |
[Route("[controller]")] | |
public class WeatherForecastController : ControllerBase | |
{ | |
[HttpGet(Name = "GetWeatherForecast")] | |
public async Task<IActionResult> GetAsync() | |
{ | |
try | |
{ | |
using var client = new TcpClient(); | |
await client.ConnectAsync("10.10.100.254", 8899); | |
using NetworkStream stream = client.GetStream(); | |
byte[] sendBytes = Convert.FromHexString("140100000001"); | |
await stream.WriteAsync(ModbusCrc(sendBytes)); | |
byte[] buffer = new byte[16]; | |
int bytesRead = await stream.ReadAsync(buffer, new CancellationTokenSource(99).Token); | |
string receivedHex = Convert.ToHexString(buffer, 0, bytesRead); | |
byte status = buffer[3]; | |
if (status == 0x00u) | |
{ | |
byte[] ffCommand = Convert.FromHexString("14050000FF00"); | |
await stream.WriteAsync(ModbusCrc(ffCommand)); | |
} | |
else if (status == 0x01u) | |
{ | |
byte[] zeroCommand = Convert.FromHexString("140500000000"); | |
await stream.WriteAsync(ModbusCrc(zeroCommand)); | |
} | |
stream.Close(); | |
client.Close(); | |
return this.Ok(new { ReceivedHex = receivedHex }); | |
} | |
catch (SocketException ex) | |
{ | |
return this.StatusCode(500, $"Socket error: {ex.Message}"); | |
} | |
catch (System.Exception ex) | |
{ | |
return this.StatusCode(500, $"Error: {ex.Message}"); | |
} | |
} | |
private static byte[] ModbusCrc(byte[] data) | |
{ | |
ushort crc = 0xFFFF; | |
foreach (byte b in data) | |
{ | |
crc ^= b; | |
for (int i = 0; i < 8; i++) | |
{ | |
if ((crc & 0x0001) != 0) | |
{ | |
crc >>= 1; | |
crc ^= 0xA001; | |
} | |
else | |
{ | |
crc >>= 1; | |
} | |
} | |
} | |
Console.WriteLine(Convert.ToHexString(BitConverter.GetBytes(crc))); | |
return [.. data, .. BitConverter.GetBytes(crc)]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment