音乐播放器
Great Wei
 
文章 标签
16

Powered by Gridea | Theme: Fog

Go Tcp客户端/服务端

服务端

package main

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

var ConnMap map[string]net.Conn
func checkError(err error){
    if  err != nil {
        fmt.Println("Error: %s", err.Error())
        os.Exit(1)
    }
}

func recvConnMsg(conn net.Conn) {
//  var buf [50]byte
    buf := make([]byte, 50)

    defer conn.Close()

    for {
        n, err := conn.Read(buf)

        if err != nil {
            fmt.Println("conn closed")
            return
        }

        fmt.Println("recv msg:", string(buf[0:n]))


        boradcastMessage(conn.RemoteAddr().String() + ":" + string(buf[0:n]))
    }
}

func boradcastMessage(message string) {
     n := []byte(message)
     for _,conn := range ConnMap {
       conn.Write(n)
     }
}

func Encode(message string) (*bytes.Buffer, error) {
    // 读取消息的长度
    var length int32 = int32(len(message))
    var pkg *bytes.Buffer = new(bytes.Buffer)
    // 写入消息头
    err := binary.Write(pkg, binary.LittleEndian, length)
    if err != nil {
        return nil, err
    }
    // 写入消息实体
    err = binary.Write(pkg, binary.LittleEndian, []byte(message))
    if err != nil {
        return nil, err
    }

    return pkg, nil
}

func Decode(reader *bufio.Reader) (string, error) {
    // 读取消息的长度
    lengthByte, _ := reader.Peek(4)
    lengthBuff := bytes.NewBuffer(lengthByte)
    var length int32
    err := binary.Read(lengthBuff, binary.LittleEndian, &length)
    if err != nil {
        return "", err
    }
    if int32(reader.Buffered()) < length+4 {
        return "", err
    }

    // 读取消息真正的内容
    pack := make([]byte, int(4+length))
    _, err = reader.Read(pack)
    if err != nil {
        return "", err
    }
    return string(pack[4:]), nil
}

func main() {
    ConnMap = make(map[string]net.Conn)
    listen_sock, err := net.Listen("tcp", "localhost:10000")
    checkError(err)
    defer listen_sock.Close()

    for {
        new_conn, err := listen_sock.Accept()
        ConnMap[new_conn.RemoteAddr().String()] = new_conn
        if err != nil {
            continue
        }

        go recvConnMsg(new_conn)
    }

}

客户端

package main

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

func checkError(err error){
    if  err != nil {
        fmt.Println("Error: %s", err.Error())
        os.Exit(1)
    }
}

func Encode(message string) (*bytes.Buffer, error) {
    // 读取消息的长度
    var length int32 = int32(len(message))
    var pkg *bytes.Buffer = new(bytes.Buffer)
    // 写入消息头
    err := binary.Write(pkg, binary.LittleEndian, length)
    if err != nil {
        return nil, err
    }
    // 写入消息实体
    err = binary.Write(pkg, binary.LittleEndian, []byte(message))
    if err != nil {
        return nil, err
    }

    return pkg, nil
}

func Decode(reader *bufio.Reader) (string, error) {
    // 读取消息的长度
    lengthByte, _ := reader.Peek(4)
    lengthBuff := bytes.NewBuffer(lengthByte)
    var length int32
    err := binary.Read(lengthBuff, binary.LittleEndian, &length)
    if err != nil {
        return "", err
    }
    if int32(reader.Buffered()) < length+4 {
        return "", err
    }

    // 读取消息真正的内容
    pack := make([]byte, int(4+length))
    _, err = reader.Read(pack)
    if err != nil {
        return "", err
    }
    return string(pack[4:]), nil
}


func onMessageRecived(conn net.Conn) {
    reader := bufio.NewReader(conn)
    for {
        msg, _ := reader.ReadString('\n')
        fmt.Println(msg)
    }
}

func main() {
    conn, err := net.Dial("tcp", "127.0.0.1:10000")
    checkError(err)
    defer conn.Close()
    go onMessageRecived(conn);
    for {
      var msg string
      fmt.Scanln(&msg)
      if msg == "quit" {
             break
      }
      message,_ := Encode(msg)
      conn.Write(message.Bytes())
    }
    fmt.Println("send msg")
}

简单的语法

package main

import (
    "fmt"
    "net/http"
    "net"
    "io/ioutil"
)

func main() {
 x, y := 3, 4
 z := sum(x, y)
 fmt.Println(z)
 n := byte('a')
 fmt.Println(n)
 a := []int{3, 1, 5}
 fmt.Println(a)
 b := make([]int, 4)
 fmt.Println(b)
 bs := []byte("a slice")
 fmt.Println(bs)
 s := []int{1, 2, 3}
 s = append(s, []int{1, 2, 3}...)
 fmt.Println(s)
 p := &x
 fmt.Println(p)
 m := map[string]int{"three":3 , "four":4}
 m["one"] = 1
 fmt.Println(m)


 if true {
    fmt.Println("yes")
 }
 switch x {
  case 0:
       fmt.Println("xxx")
 }

 for x := 0; x < 3; x++ {
  fmt.Println(x)
 }
 fmt.Println(x)

 for key, value := range s{
  fmt.Println(key, value)
 }

 defer fmt.Println(1)
 defer fmt.Println(2)

 cs := make(chan string)

 go func() {cs <- "你好" }()

 select {
 case x := <-cs:
 fmt.Println(x)
 }

 client()
}

func sum(a, b int) (sum int){
 return a + b;
}

func memory() (p *int) {
       s := make([]int, 20)
       s[3] = 7
       return &s[3]
}

type pair struct {
    x, y int
}


func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    w.Write([]byte("Y分钟golang速成!"))
}

func service() {
    go func() {
          err := http.ListenAndServe(":8080", pair{})
          fmt.Println(err)
    }()
}

func requestServer() {
    resp, err := http.Get("http://localhost:8080")
    fmt.Println(err)
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    fmt.Println("\n服务器消息: `%s`", string(body))
}

func client () {
    conn, _ := net.Dial("tcp", "127.0.0.1:9999")
    defer conn.Close()
    conn.Write([]byte("Hello world!"))
    fmt.Println("send msg")
}


请到客户端“主题--自定义配置--配置”中填入leancloud_appID和key