原文:http://blog.csdn.net/qq_15437667/article/details/51042366
1.Socket编程
以前使用Socket编程时,一般是如下步骤
- 建立socket,socket
- 绑定socket,bind
- 监听,listen
- 接受连接,accept
- 接受/发送,recv/send
go tcp版真的很省事
服务端:
就是Listen、Accept、Read/Write
客户端
就是Dial、Read/Write
1 package main 2 3 import ( 4 "fmt" 5 "net" 6 "os" 7 ) 8 9 func checkError(err error){ 10 if err != nil { 11 fmt.Println("Error: %s", err.Error()) 12 os.Exit(1) 13 } 14 } 15 16 func recvConnMsg(conn net.Conn) { 17 // var buf [50]byte 18 buf := make([]byte, 50) 19 20 defer conn.Close() 21 22 for { 23 n, err := conn.Read(buf) 24 25 if err != nil { 26 fmt.Println("conn closed") 27 return 28 } 29 30 //fmt.Println("recv msg:", buf[0:n]) 31 fmt.Println("recv msg:", string(buf[0:n])) 32 } 33 } 34 35 func main() { 36 listen_sock, err := net.Listen("tcp", "localhost:10000") 37 checkError(err) 38 defer listen_sock.Close() 39 40 for { 41 new_conn, err := listen_sock.Accept() 42 if err != nil { 43 continue 44 } 45 46 go recvConnMsg(new_conn) 47 } 48 49 }
server
1 package main 2 3 import ( 4 "fmt" 5 "net" 6 "os" 7 ) 8 9 func checkError(err error){ 10 if err != nil { 11 fmt.Println("Error: %s", err.Error()) 12 os.Exit(1) 13 } 14 } 15 16 func main() { 17 conn, err := net.Dial("tcp", "127.0.0.1:10000") 18 checkError(err) 19 defer conn.Close() 20 21 conn.Write([]byte("Hello world!")) 22 23 fmt.Println("send msg") 24 }
client
时间: 2024-10-10 11:09:12