Golang C/S代码

Jarily · · 1645 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

server

// server.go
package main

//服务器端
import (
    "bufio"
    "fmt"
    "log"
    "net" //支持通讯的包
    "strconv"
    "strings"
)

//开始服务器
func startServer() {

    fmt.Println("Launching Server...")
    //连接主机、端口,采用tcp方式通信,9183端口
    listener, err := net.Listen("tcp", "0.0.0.0:9183")
    checkError(err)
    fmt.Println("Launching Success!")
    for {
        //等待客户端接入
        conn, err := listener.Accept()
        checkError(err)
        //开一个goroutines处理客户端消息,这是golang的特色,实现并发就只go一下就好
        go doServerStuff(conn)
    }

}

//处理客户端消息
func doServerStuff(conn net.Conn) {
    //nameInfo := make([]byte, 20) //生成一个缓存数组
    //_, err := conn.Read(nameInfo)

    //name, _ := bufio.NewReader(conn).ReadString('\n')

    //name = strings.Trim(name, "\r\n")
    name := ""

    //fmt.Println("Welcome " + string(name) + " Connect Success!") //打印出来
    kstep := 0

    for {

        message, _ := bufio.NewReader(conn).ReadString('\n')

        if message == "" {
            fmt.Printf("##### %s SEND %d Data, It is already out!!!\n\n", name, kstep)
            return
        }

        flag1 := "[send " + strconv.Itoa(kstep) + "]"
        flag2 := "[recv " + strconv.Itoa(kstep) + "]"
        if strings.Contains(message, "#") {
            name = strings.Trim(message, "\r\n")
            fmt.Println("Welcome " + string(name) + " Connect Success!")
            conn.Write([]byte("Welcome " + string(name) + " Connect Success!" + "\n"))
        } else if strings.Contains(message, flag1) {
            //fmt.Printf("[正常输出] Received From %s:%s", string(name), string(message))
            newmessage := strings.ToUpper(message)
            conn.Write([]byte(flag2 + newmessage + "\n"))
            kstep++
        } else {
            fmt.Printf("[问题输出] Received From %s:%s", string(name), string(message))
        }
    }
}

//检查错误
func checkError(err error) int {
    if err != nil {
        if err.Error() == "EOF" {
            //fmt.Println("用户退出了")
            return 0
        }
        log.Fatal("an error!", err.Error())
        return -1
    }
    return 1
}
func main() {

    startServer()
}

client

package main

//客户机
import (
    "bufio"
    "bytes"
    "fmt"
    "log"
    "net"
    "strconv"
    "strings"
    "sync"
    "time"
)

var GoSum int = 10 //线程数量

var MaxStep int = 100 //单个线程传输次数

var Len int = 100 //传输数据单位长度的倍数

var wg sync.WaitGroup

//连接服务器
func connectServer(conn net.Conn, ind int) {

    name := "LS118.ZW Thread " + strconv.Itoa(ind)

    fmt.Printf("%s Connect Success!\n", name)

    fmt.Fprintf(conn, "#"+name+"\n")
    message, _ := bufio.NewReader(conn).ReadString('\n')
    if strings.Contains(message, "#") {
        fmt.Printf("%s already send name info!!!\n", name)
    }
    kstep := 0
    for {
        if kstep == MaxStep {
            conn.Close()
            defer wg.Done()
            return
        }

        flag1 := "[send " + strconv.Itoa(kstep) + "]"
        flag2 := "[recv " + strconv.Itoa(kstep) + "]"

        //fmt.Printf("%s send: ", name)

        var buffer bytes.Buffer

        buffer.WriteString("Data: ")

        for i := 1; i <= Len; i++ {
            buffer.WriteString("HEELO_WORLD ")
        }

        text := buffer.String()
        text = flag1 + text
        //fmt.Println(text)
        fmt.Fprintf(conn, text+"\n")

        message, _ := bufio.NewReader(conn).ReadString('\n')
        if strings.Contains(message, flag2) {
            //fmt.Print("Message From Server: " + message)
            kstep++
        } else {
            fmt.Print("[error]: \n" + message)
        }
    }
    //defer wg.Done()
}

//检查错误
func checkError(err error) {
    if err != nil {
        log.Fatal("an error!", err.Error())
    }
}

//主函数
func main() {
    t1 := time.Now()
    for i := 0; i < GoSum; i++ {
        conn, err := net.Dial("tcp", "0.0.0.0:9183")
        checkError(err)
        wg.Add(1)
        go connectServer(conn, i)
        defer conn.Close()
    }

    wg.Wait()
    t2 := time.Now()
    fmt.Printf("Start Time: ")
    fmt.Println(t1)
    fmt.Printf("End Time: ")
    fmt.Println(t2)
    fmt.Printf("Execute Time: ")
    fmt.Println(t2.Sub(t1))
    fmt.Printf("All goroutine already done!!! \n")
}


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:Jarily

查看原文:Golang C/S代码

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1645 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传