標籤:ror imp pac pre hello def print pms error
/
server.go /
package main
import (
"fmt"
"net"
"os"
)
func checkError(err error) {
if err != nil {
fmt.Println("Error: %s", err.Error())
os.Exit(1)
}
}
func recvUDPMsg(conn *net.UDPConn) {
var buf [20]byte
n, raddr, err := conn.ReadFromUDP(buf[0:]) if err != 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)
}
func main() {
udp_addr, err := net.ResolveUDPAddr("udp", ":9098")
checkError(err)
conn, err := net.ListenUDP("udp", udp_addr) defer conn.Close() checkError(err) //go recvUDPMsg(conn) for { recvUDPMsg(conn) }
}
/ client.go /
package main
import (
"fmt"
"net"
"os"
// "io"
)
func main() {
conn, err := net.Dial("udp", "127.0.0.1:9098")
defer conn.Close()
if err != nil {
os.Exit(1)
}
conn.Write([]byte("Hello world!")) fmt.Println("send msg") var msg [20]byte conn.Read(msg[0:]) fmt.Println("msg is", string(msg[0:10]))
}
go語言實現udp用戶端/服務端