golang入門案例之SOCKET

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
//服務端代碼
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)//發送請求} 

  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.