C# 网口通信(通过Sockets类)

文章目录

    • 1.引入Sockets
    • 2.定义TcpClient
    • 3.连接网口
    • 4.发送数据
    • 5.关闭连接

1.引入Sockets

using System.Net.Sockets;

2.定义TcpClient

private TcpClient tcpClient; // TcpClient实例
private NetworkStream stream; // 网络流,用于与服务器通信

3.连接网口

tcpClient = new TcpClient(); // TcpClient实例
{
    try
    {
        tcpClient.Connect("IP地址", "端口号");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

4.发送数据

byte[] b = Encoding.ASCII.GetBytes(liens);
stream = tcpClient.GetStream();

BinaryWriter writer = new BinaryWriter(stream);//写入流

writer.Write(b, 0, b.Length);

5.关闭连接

 tcpClient.Close();

你可能感兴趣的:(c#,服务器,网络,网口通讯,上位机)