一、阻塞模式

1、命名空间

System.Net.Sockets

2、对象声明

TcpClient dpu1TcpClient = null;//dpu1tcp客户端,TcpClient模式
NetworkStream streamToServer = null;//用于接收和发送数据的数据流对象

3、为tcp对象分配空间

dpu1TcpClient = new TcpClient();//DPU1tcp客户端初始化
4、连接服务器

按钮回调函数

{

  if (dpu1TcpClient.Connected)//如果已经连接则返回
  {
    return;
  }

  IPAddress ipaddress = IPAddress.Parse("192.168.1.1");//IP和端口
  IPEndPoint endpoint = new IPEndPoint(ipaddress, 8080);
  try
  {
    dpu1TcpClient.Connect(endpoint);
  }
  catch (SocketException e1)//连接失败
  {
    //打印e1.Message
  }

  if(dpu1TcpClient.Connected)//连接成功则开启接收线程
  {
    streamToServer = dpu1TcpClient.GetStream();//连接成功之后tcp数据流对象才能分配到空间

    //在这里开启数据接收线程,使用streamToServer来发送接收数据
  }
}

5、接收数据

线程函数

{

  Byte[] data = new Byte[2048];

  while(true)
  {
    int dataLength = streamToServer.Read(data, 0, data.Length);//这里会阻塞

    //处理数据

   }

}
6、发送数据

发送按钮回调函数

{

  string msg = "<02GS0000FF>";
  byte[] buffer = Encoding.Unicode.GetBytes(msg); //msg为发送的字符串
  streamToServer.Write(buffer, 0, buffer.Length); //发往服务器

}

 

相关文章:

  • 2021-05-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-06
  • 2021-07-25
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-02
  • 2021-07-13
  • 2022-01-19
  • 2022-01-19
相关资源
相似解决方案