需要使用Socket类来创建和连接TCP/IP套接字,并使用Send和Receive方法来发送和接收数据。还需要引用System.Net和System.Net.Sockets命名空间。
以下是一个示例代码,它发送一个字符串消息到指定的IP地址和端口,并接收返回消息。文章来源:https://www.toymoban.com/news/detail-730806.html
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public string sendTCPMessage (string ip_address, string port, string message)
{
try
{
// Convert the ip address and port to an IPEndPoint object
int converted_port = Convert.ToInt32 (port);
IPAddress converted_ip = IPAddress.Parse(ip_address);
IPEndPoint ipEndPoint = new IPEndPoint(converted_ip, converted_port);
// Create a TCP client socket and connect to the server
using Socket client = new(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
await client.ConnectAsync(ipEndPoint);
// Encode the message to a byte array and send it
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(messageBytes, SocketFlags.None);
// Receive the response from the server
byte[] responseBytes = new byte[1024];
int bytesReceived = await client.ReceiveAsync(responseBytes, SocketFlags.None);
string response = Encoding.UTF8.GetString(responseBytes, 0, bytesReceived);
// Print the response to the console
Console.WriteLine("Received: {0}", response);
// Set the success flag to true
success = true;
}
catch (Exception e)
{
// Print the exception to the console
Console.WriteLine(e.Message);
}
return response;
}
了解更多C#可以访问C#的官方教程
本文也参考了C#的官方教程: 微软C#关于TCP/IP的使用文章来源地址https://www.toymoban.com/news/detail-730806.html
到了这里,关于C#向指定的ip地址通过TCP/IP协议发送和接受信息的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!