golang入门案例之SOCKET

Posted 打败大魔王

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang入门案例之SOCKET相关的知识,希望对你有一定的参考价值。

//服务端代码
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的主要内容,如果未能解决你的问题,请参考以下文章

gRPC之GoLang入门HelloWord(排版整理)

golang代码片段(摘抄)

Golang如何体现面向对象三大特性之继承?

window下golang使用gRPC入门案例

Python 之 Socket编程(TCP/UDP)

Golang如何体现面向对象三大特征之多态?