這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
//服務端代碼
package mainimport ("fmt""net""log""os""encoding/binary")func main() {//建立socket,監聽連接埠netListen, err := net.Listen("tcp", "localhost:8090")CheckError(err)defer netListen.Close()Log("Waiting for clients")for {conn, err := netListen.Accept()if err != nil {continue}Log(conn.RemoteAddr().String(), " tcp connect success")handleConnection(conn)}}//處理串連func handleConnection(conn net.Conn) {//buffer := make([]byte, 2048)for {var pi float64var a uint16err := binary.Read(conn, binary.LittleEndian, &pi)//讀取浮點數err = binary.Read(conn, binary.LittleEndian, &a)//讀取整數CheckError(err)if err != nil {Log(conn.RemoteAddr().String(), " connection error: ", err)return}Log(conn.RemoteAddr().String(), "receive data string:\n", (pi), ", uint16 a= " , a)}}func Log(v ...interface{}) {log.Println(v...)}func CheckError(err error) {if err != nil {fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())os.Exit(1)}}
用戶端:
package mainimport ( "fmt" "net" "os" "bytes" "encoding/binary")var x float32 = 1.2 //1.2func init() { //1.3 fmt.Printf("p1 package, x:%f\n", x) //1.4}func Donothing() { fmt.Println("do nothing.\n")}func sender(conn net.Conn) { var pi float64 = 3.141592653589793 buf := new(bytes.Buffer) err := binary.Write(buf, binary.LittleEndian, pi)//向buf中寫入浮點數 if err != nil { fmt.Println("binary.Write failed:", err) } // 這裡可以繼續往buf裡寫, 都存在buf裡 err = binary.Write(buf, binary.LittleEndian, uint16(12345))//向buf中寫入整數 if err != nil { fmt.Println("binary.Write failed:", err) } fmt.Print(buf.Bytes()) // [24 45 68 84 251 33 9 64] fmt.Println("send over") conn.Write(buf.Bytes())//向socket中寫入buf //words := "hello world!" //conn.Write([]byte(words))}func main() { server := "127.0.0.1:8090" tcpAddr, err := net.ResolveTCPAddr("tcp4", server)//轉換成TCP地址 if err != nil { fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error()) os.Exit(1) } conn, err := net.DialTCP("tcp", nil, tcpAddr)//進行TCP串連 if err != nil { fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error()) os.Exit(1) } fmt.Println("connect success") sender(conn)//發送請求}