C# TCP/IP协议

时间:2024-02-23 12:16:39

在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)