首页 > 其他分享 >Go - Creating a UDP Server

Go - Creating a UDP Server

时间:2023-10-16 19:33:24浏览次数:25  
标签:UDP Creating err server connection client net Server

Problem: You want to create a UDP server to receive data from a UDP client.


Solution: Use the ListenPacket function in the net package to listen for incoming packets. Then use the ReadFrom method of the PacketConn interface to read data from the connection. You can also use the WriteTo method to write data to the connection.

 

UDP is a connectionless protocol. This means there is no connection between the client and the server. The client sends data to the server and the server sends data back to the client. Neither the client nor the server knows if the server or client received the data or not. 

A UDP server in Go is similar to a TCP server. The main difference is that you use the net.ListenPacket function instead of the net.Listen function:

func   main ()   { 
      conn ,   err   :=   net . ListenPacket ( "udp" ,   ":9001" ) 
      if   err   !=   nil   { 
          log . Fatal ( err ) 
      } 
      defer   conn . Close () 
      buf   :=   make ([] byte ,   1024 ) 
      for   { 
          _ ,   addr ,   err   :=   conn . ReadFrom ( buf ) 
          if   err   !=   nil   { 
              log . Fatal ( err ) 
          } 
          log . Printf ( "Received  %s  from  %s" ,   string ( buf ),   addr ) 
          conn . WriteTo ([] byte ( "Hello  from  UDP  server" ),   addr ) 
      } 
}

The net.ListenPacket function returns a net.PacketConn interface, which is a packet - oriented network connection. Unlike the net.Conn interface, net.PacketConn is not a Reader or Writer because it doesn’t have Read or Write methods. Instead, it has ReadFrom and WriteTo methods to read and write data from and to the connection. 

You can test the server. Start this on one terminal:

$  go  run  main.go

Use the nc command to send data to it. In another terminal, run the following command as the client:

$  echo  "Hello  from  UDP  client"  |  nc  - u  localhost  9001

You should see “Received Hello from UDP client” printed out on the server side, and “Hello from UDP server” printed out on the client side. 

As in the TCP server, your UDP server is listening on both IPv4 and IPv6. To show this you’ll use the - 6 flag to force nc to use IPv6:

$  echo  "Hello  from  UDP  client"  |  nc  - u  - 6  localhost  9001

You should see the same output as before. 

Besides using net.ListenPacket you can also use the net.ListenUDP function to create a UDP server:

func   main ()   { 
      addr ,   err   :=   net . ResolveUDPAddr ( "udp" ,   ":9001" ) 
      if   err   !=   nil   { 
          log . Fatal ( err ) 
      } 
      conn ,   err   :=   net . ListenUDP ( "udp" ,   addr ) 
      if   err   !=   nil   { 
          log . Fatal ( err ) 
      } 
      defer   conn . Close () 
      buf   :=   make ([] byte ,   1024 ) 
      for   { 
          _ ,   addr ,   err   :=   conn . ReadFromUDP ( buf ) 
          if   err   !=   nil   { 
              log . Fatal ( err ) 
          } 
          log . Printf ( "Received  %s  from  %s" ,   string ( buf ),   addr ) 
          conn . WriteToUDP ([] byte ( "Hello  from  UDP  server" ),   addr ) 
      } 
}

Unlike the net.ListenPacket , though, the net.ListenUDP function takes a net.UDPAddr as an argument. First, use the net.ResolveUDPAddr function to resolve and create the address. Then use the net.ListenUDP function to create the connection. Instead of net.PacketConn you get a net.UDPConn interface. The net.UDPConn struct implements both the net.PacketConn and net.Conn interfaces, meaning it has both ReadFrom and WriteTo methods and Read and Write methods. In addition, it has ReadFromUDP and WriteToUDP methods to read and write data from and to the connection. 

The net.ListenPacket function is more generic and can be used to create a UDP server, but it is also used to create other types of servers such as IP and Unix domain sockets. The net.ListenUDP function is more specific and can only be used to create a UDP server. 

At this point, you might be confused about why net.UDPConn implements both the net.PacketConn and net.Conn interfaces. After all, net.UDPConn is a packet - oriented connection whereas net.Conn is a stream - oriented connection, which is also implemented by the net.TCPConn struct. How can a connection be both packet - oriented and stream - oriented at the same time? 

This comes from the original Berkeley, sockets API that has become the standard in Unix - like systems where sockets are stream - oriented. Both UDP and TCP are implemented on top of sockets so they both implement the net.Conn interface.

 

标签:UDP,Creating,err,server,connection,client,net,Server
From: https://www.cnblogs.com/zhangzhihui/p/17768182.html

相关文章

  • linux安装myql-server及libmysqlclient
    1.去官网下载对应的仓库源https://dev.mysql.com/downloads/下面以centos8为例#仓库下载直链为https://dev.mysql.get/{具体的仓库名}wgethttps://dev.mysql.com/get/mysql80-community-release-el8-8.noarch.rpmyuminstall./mysql80-community-release-el8-8.noarch.r......
  • linux 安装Apache HTTP Server 2.4.48版本详细教程
    编译前准备首先下载:httpd-2.4,apr-1.4以上,apr-util-1.4以上httpd-2.4.48.tar.gz下载地址:https://downloads.apache.org/httpd/httpd-2.4.48.tar.gzapr-1.7.0.tar.gz下载地址:https://downloads.apache.org/apr/apr-1.7.0.tar.gzapr-util-1.6.1.tar.gz下载地址:https://downlo......
  • SQL server CONVERT()函数关于data用法
    CONVERT()函数是把日期转换为新数据类型的通用函数。CONVERT()函数可以用不同的格式显示日期/时间数据。语法:CONVERT(data_type(length),data_to_be_converted,style)       data_type(length) 规定目标数据类型(带有可选的长度)。data_to_be_converte......
  • Go - Creating a TCP Client
    Problem: YouwanttocreateaTCPclienttosenddatatoaTCPserver.Solution: UsetheDialfunctioninthenetpackagetoconnecttoaTCPserver. CreatingaTCPclientissimilartocreatingaTCPserverbutevensimpler.Themaindifferenceistha......
  • HarmonyOS/OpenHarmony原生应用开发-华为Serverless服务支持情况(四)
    文档中的TS作者认为就是ArkTS之意。一、云存储AppGalleryConnect(简称AGC)云存储是一种可伸缩、免维护的云端存储服务,可用于存储图片、音频、视频或其他由用户生成的内容。借助云存储服务,您可以无需关心存储服务器的开发、部署、运维、扩容等事务,大大降低了应用使用存储的门槛,让您可......
  • Qt/C++编写物联网组件/支持modbus/rtu/tcp/udp/websocket/mqtt/多线程采集
    一、功能特点支持多种协议,包括Modbus_Rtu_Com/Modbus_Rtu_Tcp/Modbus_Rtu_Udp/Modbus_Rtu_Web/Modbus_Tcp/Modbus_Udp/Modbus_Web等,其中web指websocket。支持多种采集通讯方式,包括串口和网络等,可自由拓展其他方式。自定义采集间隔(精确到毫秒)和超时次数,超时后自动将离线的文件......
  • update left join 在MySQL和SQL Server使用方式区别
    (1)MySQL使用UPDATEhayl_service_infot1leftjoinhayl_Old_infot2ont1.CERT_NO=t2.CERT_NOsett1.AAP0112=t2.ADDRESSwheret1.AAP0112=''(2)SQLServers使用UPDATEhayl_service_infosetAAP0112=t2.ADDRESSfromhayl_service_infot1leftjoin......
  • WINCC V7.5 SP2 webnavigator server无法安装的解决-操作系统版本很重要
    这一篇学习笔记我在新浪博客记录过,地址是 WINCCV7.5SP2webnavigatorserver无法安装的解决-操作系统版本很重要_来自金沙江的小鱼_新浪博客(sina.com.cn)在这里再次记录一遍。昨天在办公室计算机上的虚拟机安装windows101903专业版,然后安装WINCC7.5SP2,想安装webnavigator......
  • SQL Server数据库多种方式查找重复记录
    示例:表stuinfo,有三个字段recno(自增),stuid,stuname 建该表的Sql语句如下: CREATETABLE[StuInfo]([recno][int]IDENTITY(1,1)NOTNULL,[stuid][varchar](10)COLLATEChinese_PRC_CI_ASNOTNULL,[stuname][varchar](10)COLLATEChinese_PRC_CI_ASNOTNULL)ON[PRIMAR......
  • 升级Lync Server 2013到Skype for Business 2019(十一)
    写在前面本章将介绍如何将LyncServer2013旧有边缘服务,切换到新的SkypeforBusiness2019边缘服务器上。切换SkypeforBusiness2019服务器添加SkypeforBusiness2019服务器公网DNS。这些DNS主要包括如下内容:项目DNS配置类型IP外部访问access.contoso.comA公网IP地址外部Web会......