Golang C/S代碼

來源:互聯網
上載者:User

server

// server.gopackage 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")}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.