Go TCP Server示例

4月开始了Go语言的学习。

在五年的工作生涯中,主要用过C、Shell、Python、Java。 体验过Java的臃肿,C的简陋,Python的性能;Go的一些改进,给我带来了惊喜。

我觉得是我深入学习的倒数第二门编程语言,以后很难有精力和机会去学习更多的编程语言了。 为什么是倒数第二,也许我还期待着一门更好的语言。

参照网上的资料,实现一个Go TCP Server例子。

package main

import (
    "bufio"
    "fmt"
    "net"
    "os"
    "strings"
)

const (
    CONN_HOST = "localhost"
    CONN_PORT = "8888"
    CONN_TYPE = "tcp"
)

func main() {
    // Listen for incoming connections
    listener, err := net.Listen(CONN_TYPE, CONN_HOST+":"+CONN_PORT)
    if err != nil {
        fmt.Println("Error listening:", err.Error())
        os.Exit(1)
    }

    // Close the listener when the function exit
    defer listener.Close()

    fmt.Println("Start listening on " + CONN_HOST + ":" + CONN_PORT)
    for {
        // Listen for an incoming connection
        conn, err := listener.Accept()
        if err != nil {
            fmt.Println("Error accepting:", err.Error())
            os.Exit(1)
        }
        // Handle connection in a new goroutine
        go handleRequest2(conn)
    }
}

// Handle incoming requests
func handleRequest(conn net.Conn) {
    fmt.Printf("Serving %s\n", conn.RemoteAddr().String())

    // Close tbe connection when the function ends
    defer func() {
        fmt.Println("Closing connection...")
        conn.Close()
    }()

    // Make a buffer to store incoming data
    buf := make([]byte, 1024)

    // Read the incoming connection into the buffer
    reqLen, err := conn.Read(buf)
    if err != nil {
        fmt.Println("Error reading:", err.Error())
        return
    }

    fmt.Println("Receive data length:", reqLen, "content:", string(buf[:reqLen]))
    // Send a response back
    conn.Write([]byte("Hello, World!\n"))
}

// Handle incoming requests
func handleRequest2(conn net.Conn) {
    fmt.Printf("Serving %s\n", conn.RemoteAddr().String())

    // Close tbe connection when the function ends
    defer func() {
        fmt.Println("Closing connection...")
        conn.Close()
    }()

    // The for loop makes sure that the TCP client will be served for as long as the TCP client desires.
    for {
        recvData, err := bufio.NewReader(conn).ReadString('\n')
        if err != nil {
            fmt.Println("Error reading:", err.Error())
            return
        }

        temp := strings.TrimSpace(string(recvData))
        if temp == "STOP" {
            fmt.Println("Received STOP msg, will exit...")
            break
        }

        fmt.Println("Received content:", temp)
        // Send a response back
        conn.Write([]byte("Hello, World!\n"))
    }
}

测试TCP

nc localhost 8888
本文由 络壳 原创或整理,转载请注明出处