1. 程式人生 > >golang入門案例之SOCKET

golang入門案例之SOCKET

int div 進行 lec ont func 轉換 exit oca

//服務端代碼
package main import ( "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 float64 var a uint16 err := 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 main

import (
   "fmt"
   "net"
   "os"
   "bytes"
   "encoding/binary"
)


var x float32 = 1.2 //1.2

func 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)//發送請求

}
 

  

golang入門案例之SOCKET