Go Socket Programming Practice: UDP server and client implementations

Source: Internet
Author: User
Tags rfc
This is a creation in Article, where the information may have evolved or changed.

In the previous article Go Socket programming Practice: TCP Server and client implementation, we implemented an echo server, and also implemented a client to access the server.
This article explains how to implement a UDP server and client.
The protocol we're using this time is RFC 868,
This protocol provides a site-independent, machine-readable date and time information. The time service returns a 32-bit number that is the number of seconds from midnight January 1, 1900 to the present.
RFC 868 defines the time protocol to use port PNS, both TCP and UDP protocols.

There are also two RFC protocols on time/date.
NTP (RFC 1305) is a network time protocol that provides precise time synchronization.
Daytime (RFC 867) listens on TCP port 13, returning the date and time of the acsii format.

In the TCP/IP model, UDP provides a simple interface above the network layer and below the application layer. UDP only provides unreliable delivery of data, once it sends the application to the network layer of data sent out, do not retain data backup (so UDP is sometimes considered unreliable datagram protocol). UDP only adds multiplexing and data validation (fields) to the head of the IP datagram.

The UDP header field consists of 4 parts, two of which are optional. Each 16bit source port and destination port are used to mark the sending and receiving application processes. Because UDP does not need to be answered, the source port is optional and zero if the source port is not used. Behind the destination port is a fixed length field in bytes that specifies the length of the data portion of the UDP datagram, with a minimum length of 8byte. The first remaining 16bit is used to do checksum (Checksum) with the header and Data section, which is optional, but is generally used in practical applications.

Due to the lack of reliability and the non-connection-oriented protocol, UDP applications must generally allow a certain amount of drops, errors, and copies to be affixed. However, some applications, such as TFTP, must add fundamental and reliable mechanisms to the application layer if needed. However, most UDP applications do not require a reliable mechanism and may even degrade performance by introducing a reliable mechanism. Streaming media (streaming technology), instant multimedia games, and IP telephony (VoIP) must be typical UDP applications. If an application requires high reliability, then the Transmission Control Protocol (TCP protocol) can be used instead of UDP.

Due to the lack of congestion control (congestion), network-based mechanisms are needed to reduce the congestion collapse effect caused by runaway and high-speed UDP traffic loads. In other words, because UDP senders are not able to detect congestion, network-based devices such as routers that use packet queuing and drop technology tend to be effective tools for reducing UDP over-large traffic. The Datagram Congestion Control Protocol (DCCP) is designed to mitigate this potential problem by increasing host congestion control in high-rate UDP streams such as streaming media types.

Many of the key applications on a typical network that use the UDP protocol are somewhat similar. These applications include domain Name System (DNS), Simple Network Management Protocol (SNMP), Dynamic Host Configuration Protocol (DHCP), Routing Information Protocol (RIP), and some video streaming services, and so on. 、

Server

The difference between processing a UDP socket and a TCP socket in the Go Language pack is that the server side handles multiple client request packets differently, and UDP lacks the Accept function for client connection requests. The other basic is almost identical, only TCP is replaced by UDP. Several of the main functions of UDP are as follows:

123
func string, Laddr *udpaddr) (c *udpconn, err OS. Error)func (c *udpconn) readfromudp (b []byteint, addr *udpaddr, err os. Errorfunc (c *udpconn) writetoudp (b []byteint, err os. Error)

net.ListenUDPReturns UDPConn an object that can read data and send data to the appropriate client (specify UDPADDR).

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
 PackageMainImport("Encoding/binary""Flag""FMT""NET""OS""Time")varHost = flag. String ("Host","","Host")varPort = flag. String ("Port","Panax Notoginseng","Port")funcMain () {flag. Parse () addr, err: = Net. RESOLVEUDPADDR ("UDP", *host+":"+*port)ifErr! =Nil{FMT. Println ("Can ' t resolve address:", err) OS. Exit(1)}conn, err: = Net. LISTENUDP ("UDP", addr)ifErr! =Nil{FMT. Println ("Error Listening:", err) OS. Exit(1)}deferConn. Close () for{handleclient (conn)}}funcHandleclient (Conn *net. Udpconn) {Data: = Make([]byte,1024x768) n, remoteaddr, err: = conn. READFROMUDP (data)ifErr! =Nil{FMT. Println ("failed to read UDP msg because of"Err. Error ())return}daytime: = time. Now (). Unix () fmt. PRINTLN (n, remoteaddr) B: = Make([]byte,4) binary. Bigendian.putuint32 (b,UInt32(daytime)) Conn. WRITETOUDP (b, remoteaddr)}

The number of times is 64 bits and needs to be converted to a 32-bit byte.

Executing the go run timeserver.go boot server

Client

The client code is similar to TCP.

12345
func string) (*udpaddr, OS.) Error)funcstring, Laddr, raddr *udpaddr) (c *udpconn, err OS. Error)funcstring, Laddr *udpaddr) (c *udpconn, err OS. Error)func (c *udpconn) Read (b []byte) (int, error)func (c *udpconn) Write (b []< C12>byte) (int, error)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
 PackageMainImport("Encoding/binary""Flag""FMT""NET""OS""Time")varHost = flag. String ("Host","localhost","Host")varPort = flag. String ("Port","Panax Notoginseng","Port")//go run Timeclient.go-host time.nist.govfuncMain () {flag. Parse () addr, err: = Net. RESOLVEUDPADDR ("UDP", *host+":"+*port)ifErr! =Nil{FMT. Println ("Can ' t resolve address:", err) OS. Exit(1)}conn, err: = Net. DIALUDP ("UDP",Nil, addr)ifErr! =Nil{FMT. Println ("Can ' t dial:", err) OS. Exit(1)}deferConn. Close () _, err = conn. Write ([]byte(""))ifErr! =Nil{FMT. Println ("failed:", err) OS. Exit(1)}data: = Make([]byte,4) _, Err = conn. Read (data)ifErr! =Nil{FMT. Println ("failed to read UDP msg because of", err) OS. Exit(1)}t: = Binary. Bigendian.uint32 (data) fmt. Println (time. Unix (Int64(t),0). String ()) OS. Exit(0)}

Executes the go run timeclient.go test UDP.
You can also use the public network time server test:go run timeclient.go -host time.nist.gov

Reference

    1. https://tools.ietf.org/html/rfc868
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.