Home > Backend Development > C#.Net Tutorial > Detailed explanation of the sample code for synchronous communication based on C#'s UDP protocol

Detailed explanation of the sample code for synchronous communication based on C#'s UDP protocol

黄舟
Release: 2017-03-23 11:38:10
Original
2005 people have browsed it

This article mainly introduces the synchronization implementation code of the UDP protocol based on C#. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

1. Summary

Summary of synchronous communication based on C# UDP protocol.

2. Experimental platform

Visual Studio 2010

3. Experimental principle

The difference between UDP transmission protocol and TCP transmission protocol can be found in the relevant documents and will not be repeated here.

4. Example

4.1 Using socket to implement UDP

Because UDP is a wireless The connection protocol. Therefore, in order for the server application to send and receive UDP packets, two things need to be done:

(1) Create a Socket object;

(2) Bind the created socket object to the local IPEndPoint.

After completing the above steps, the created socket will be able to receive incoming UDP data packets on IPEndPoint, or send outgoing UDP data packets to any other device in the network. When communicating using UDP, no connection is required. Because there is no connection established between remote hosts, UDP cannot use the standard Send() and Receive()t socket methods, but uses two other methods: SendTo() and ReceiveFrom().

SendTo() method specifies the data to be sent and the IPEndPoint of the target machine. This method can be used in several different ways, depending on the specific application, but at least the packet and target machine must be specified. As follows:

SendTo(byte[] data,EndPoint Remote)
Copy after login

The ReceiveFrom() method is similar to the SendTo() method, but the way of using the EndPoint object declaration is different. Using ref modification, what is passed is not an EndPoint object, but the parameter is passed to an EndPoint object.

UDP application is not a real server and client in the strict sense, but an equal relationship, that is, there is no primary and secondary relationship. For the sake of simplicity, we still call the following application a UDP server.

Server-side code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace UDP
{
 class Program
 {
  static void Main(string[] args)
  {
   int recv;
   byte[] data = new byte[1024];

   //得到本机IP,设置TCP端口号   
   IPEndPoint ip = new IPEndPoint(IPAddress.Any, 8001);
   Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

   //绑定网络地址
   newsock.Bind(ip);

   Console.WriteLine("This is a Server, host name is {0}", Dns.GetHostName());

   //等待客户机连接
   Console.WriteLine("Waiting for a client");

   //得到客户机IP
   IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
   EndPoint Remote = (EndPoint)(sender);
   recv = newsock.ReceiveFrom(data, ref Remote);
   Console.WriteLine("Message received from {0}: ", Remote.ToString());
   Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

   //客户机连接成功后,发送信息
   string welcome = "你好 ! ";

   //字符串与字节数组相互转换
   data = Encoding.ASCII.GetBytes(welcome);

   //发送信息
   newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
   while (true)
   {
    data = new byte[1024];
    //发送接收信息
    recv = newsock.ReceiveFrom(data, ref Remote);
    Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
    newsock.SendTo(data, recv, SocketFlags.None, Remote);
   }
  }

 }
}
Copy after login

For the UDP server program to receive incoming messages, the program must be bound to the UDP port specified in the local system. This is accomplished by creating an IPEndPoint object with the appropriate local IP address, and the appropriate UDP port number. The UDP server in the above example program can receive any incoming UDP packet from the network on port 8001.

UDP client program is very similar to server program.

Because the client does not need to wait for incoming data on the specified UDP port, therefore, the Bind() method is not used, but a UDP port randomly designated by the system when sending data is used, and The same port receives the returned message. When developing products, specify a set of UDP ports for the client so that the server and client programs use the same port number. The UDP client program first defines an IPEndPoint, and the UDP server will send data packets to this IPEndPoint. If you are running a UDP server program on a remote device, the appropriate IP address and UDP port number information must be entered in the IPEndPoint definition.

Client code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace UDPClient
{
 class Program
 {
  static void Main(string[] args)
  {
   byte[] data = new byte[1024];
   string input, stringData;

   //构建TCP 服务器
   Console.WriteLine("This is a Client, host name is {0}", Dns.GetHostName());

   //设置服务IP,设置TCP端口号
   IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8001);

   //定义网络类型,数据连接类型和网络协议UDP
   Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

   string welcome = "你好! ";
   data = Encoding.ASCII.GetBytes(welcome);
   server.SendTo(data, data.Length, SocketFlags.None, ip);
   IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
   EndPoint Remote = (EndPoint)sender;

   data = new byte[1024];
   //对于不存在的IP地址,加入此行代码后,可以在指定时间内解除阻塞模式限制
   int recv = server.ReceiveFrom(data, ref Remote);
   Console.WriteLine("Message received from {0}: ", Remote.ToString());
   Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
   while (true)
   {
    input = Console.ReadLine();
    if (input == "exit")
     break;
    server.SendTo(Encoding.ASCII.GetBytes(input), Remote);
    data = new byte[1024];
    recv = server.ReceiveFrom(data, ref Remote);
    stringData = Encoding.ASCII.GetString(data, 0, recv);
    Console.WriteLine(stringData);
   }
   Console.WriteLine("Stopping Client.");
   server.Close();
  }

 }
}
Copy after login

The implementation logic of the above code is: after the relevant settings are completed, the server first sends information to the client, then the client sends a string through the keyboard, and the server receives After arriving, it is sent to the client, and so loops.

4.2 Use the UDPClient class to implement

Server-side code:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class Custom
{
 // 设置IP,IPV6
 private static readonly IPAddress GroupAddress = IPAddress.Parse("IP地址");
 // 设置端口
 private const int GroupPort = 11000;

 private static void StartListener()
 {
  bool done = false;

  UdpClient listener = new UdpClient();

  IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort);

  try
  {
   //IPV6,组播
   listener.JoinMulticastGroup(GroupAddress);

   listener.Connect(groupEP);

   while (!done)
   {
    Console.WriteLine("Waiting for broadcast");

    byte[] bytes = listener.Receive(ref groupEP);

    Console.WriteLine("Received broadcast from {0} :\n {1}\n", groupEP.ToString(), Encoding.ASCII.GetString(bytes, 0, bytes.Length));
   }

   listener.Close();

  }
  catch (Exception e)
  {
   Console.WriteLine(e.ToString());
  }

 }

 public static int Main(String[] args)
 {
  StartListener();

  return 0;
 }
}
Copy after login

Client-side code:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class Client
{

 private static IPAddress GroupAddress = IPAddress.Parse("IP地址");

 private static int GroupPort = 11000;

 private static void Send(String message)
 {
  UdpClient sender = new UdpClient();

  IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort);

  try
  {
   Console.WriteLine("Sending datagram : {0}", message);

   byte[] bytes = Encoding.ASCII.GetBytes(message);

   sender.Send(bytes, bytes.Length, groupEP);

   sender.Close();

  }
  catch (Exception e)
  {
   Console.WriteLine(e.ToString());
  }

 }

 public static int Main(String[] args)
 {
  Send(args[0]);

  return 0;
 }
}
Copy after login

The above code needs explanation Yes:

(1) The above code is a multicast mode based on IPV6 address. Broadcast in IPv4 can cause network performance degradation or even broadcast storm. The concept of broadcast does not exist in IPv6, and is replaced by multicast and anycast.

(2) IPV6 address representation method:

a) X:X:X:X:X:X:X:X (each X represents a 16-digit hexadecimal number) , not case-sensitive;

b) The leading 0 can be omitted, for example, 09C0 can be written as 9C0, 0000 can be written as 0;

c) Fields with consecutive 0s can be represented by:: Instead, :: can only appear once in the entire address. For example, FF01:0:0:0:0:0:0:1 can be abbreviated as FF01::1.

(3) If it is in the form of a form, it is recommended to use this format, otherwise it may crash when receiving data.

// 创建一个子线程

   Thread thread = new Thread(
    delegate()
    {
     try
     {
      //在这里写你的代码
     }
     catch (Exception )
     {

     }
    }
   );

   thread.Start();
Copy after login

The above is the detailed content of Detailed explanation of the sample code for synchronous communication based on C#'s UDP protocol. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template