C# TCP/IP协议

在C#中编写TCP/IP通信 

//开启监听各个网络的连接是否成功
 //开启服务端,监听,并且进入监听线程
 try
 {             

     IPAddress ip = IPAddress.Parse(HostAddress);
     IPEndPoint ipe = new IPEndPoint(ip, HostPort);

     
     m_services = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     m_services.Bind(ipe);
     m_services.Listen(0);
 }
 catch (Exception ex)
 {
     MessageBox.Show("服务器打开失败,请打开设置页面重新设置服务器地址");
     return;
 }

//发送8位的16进制数据

                    byte[] NetRd = { 0x01, 0x02, 0x00, 0x00, 0x00, 0x18, 0x78, 0x00 };

                    Connect_Socket.Send(NetRd);

Socket connection = (Socket)sender;
                    IPEndPoint IPend = (IPEndPoint)connection.RemoteEndPoint;
                    IPAddress IP = IPend.Address;

                    byte[] buffer = new byte[1024 * 2];
                    int aa = -1;

 connection.ReceiveTimeout = 10000;
    string input;

if (connection.Connected)
{
                //如果连接不存在,则显示设备停止运行,并且退出该程序
                aa = connection.Receive(buffer);
    input = Encoding.UTF8.GetString(buffer, 0, aa);
}

socket.Shutdown(SocketShutdown.Both)

相关推荐

  1. LLMNR协议、MDNS协议、NBNS协议

    2024-02-22 23:48:02       37 阅读
  2. UDP<span style='color:red;'>协议</span>

    UDP协议

    2024-02-22 23:48:02      72 阅读
  3. TCP<span style='color:red;'>协议</span>

    TCP协议

    2024-02-22 23:48:02      52 阅读
  4. IP<span style='color:red;'>协议</span>

    IP协议

    2024-02-22 23:48:02      67 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-22 23:48:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-22 23:48:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-22 23:48:02       82 阅读
  4. Python语言-面向对象

    2024-02-22 23:48:02       91 阅读

热门阅读

  1. 2024年开发踩坑记录

    2024-02-22 23:48:02       46 阅读
  2. C语言技巧总结(自用)

    2024-02-22 23:48:02       56 阅读
  3. Web基础

    Web基础

    2024-02-22 23:48:02      54 阅读
  4. 深入理解Python爬虫的Response对象

    2024-02-22 23:48:02       55 阅读
  5. P5719 【深基4.例3】分类平均

    2024-02-22 23:48:02       54 阅读
  6. 开源软件的影响力

    2024-02-22 23:48:02       48 阅读
  7. linux命令--pidof

    2024-02-22 23:48:02       49 阅读
  8. springboot接收base64文件并上传

    2024-02-22 23:48:02       40 阅读
  9. 【达梦数据库】查看pesg回滚段信息的视图和SQL

    2024-02-22 23:48:02       53 阅读
  10. 数学术语之源——插值(interpolation)

    2024-02-22 23:48:02       56 阅读