This is a creation in Article, where the information may have evolved or changed.
Go easy UDP socket client and server
1.Socket programming
Before using socket programming, it is generally the following steps
- Establish Socket,socket
- Binding Socket,bind
- Listen, listen.
- Accept the connection.
- Accept/Send, Recv/send
The go language has been abstracted and encapsulated, and it may not be very adaptable to start contact (for example, I think the API is hard to find when I use it for the first day ...). Recommended reference document), and later found it very cool to use.
Simply put, the client saves a lot! The client only needs to call net. Dial () can, server I still need to find out here, but it is very simple, but the process feeling is not simplified-
Nonsense not much to say directly on the code
2.Server Terminal
Import("OS" "FMT" "NET")funcCheckError (err Error) {ifErr! =Nil{FMT. Println ("Error:%s"Err. Error ()) OS. Exit(1) }}funcRECVUDPMSG (Conn *net. Udpconn) {varBuf[]byteN, raddr, err: = conn. READFROMUDP (buf[0:])ifErr! =Nil{return} FMT. Println ("MSG is",string(buf[0: n]))//writetoudp //func (c *udpconn) writetoudp (b []byte, addr *udpaddr) (int, error)_, Err = conn. WRITETOUDP ([]byte("Nice-to-see U"), raddr) CheckError (ERR)}funcMain () {udp_addr, err: = Net. RESOLVEUDPADDR ("UDP",": 11110") CheckError (ERR) conn, err: = Net. LISTENUDP ("UDP", UDP_ADDR)deferConn. Close () checkerror (ERR)//go RECVUDPMSG (conn)RECVUDPMSG (conn)}
Process
- First through net. Resolveudpaddr Creating a listening address
- Net. LISTENUDP Creating a listener link
- And then through Conn. READFROMUDP and CONN.WRITETOUDP send and receive UDP messages
3.Client Terminal
PackageMainImport("OS" "FMT" "NET"//"IO")funcMain () {conn, err: = Net. Dial ("UDP","127.0.0.1:11110")deferConn. Close ()ifErr! =Nil{OS. Exit(1)} conn. Write ([]byte("Hello world!") FMT. Println ("Send msg")varMsg[]byteConn. Read (msg[0:]) fmt. Println ("MSG is",string(msg[0: Ten]))}
The client is very simple, first through net. Dial ("UDP", "127.0.0.1:11110"), create a socket that sends messages to the native 11110 port, and then use Conn. Write and Conn.read receive the package, of course conn.readfromudp and CONN.WRITETOUDP is also possible