码迷,mamicode.com
首页 > 其他好文 > 详细

golang入门案例之SOCKET

时间:2018-01-15 22:41:10      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:body   print   地址   exit   make   enc   pad   send   lang   

//服务端代码
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

标签:body   print   地址   exit   make   enc   pad   send   lang   

原文地址:https://www.cnblogs.com/nazhizq/p/8289769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!