Golang笔记

用Go 写一个简单的TCP 服务

Go 实现的一个简单的TCP 服务

package main

import (
    "bytes"
    "fmt"
    "net"
    "os"
    "strconv"
)

const (
    CONN_HOST = ""
    CONN_PORT = "3333"
    CONN_TYPE = "tcp"
)

func main() {
    // Listen for incoming connections.
    l, err := net.Listen(CONN_TYPE, ":"+CONN_PORT)
    if err != nil {
        fmt.Println("Error listening:", err.Error())
        os.Exit(1)
    }
    // Close the listener when the application closes.
    defer l.Close()
    fmt.Println("Listening on " + CONN_HOST + ":" + CONN_PORT)
    for {
        // Listen for an incoming connection.
        conn, err := l.Accept()
        if err != nil {
            fmt.Println("Error accepting: ", err.Error())
            os.Exit(1)
        }

        //logs an incoming message
        fmt.Printf("Received message %s -> %s \n", conn.RemoteAddr(), conn.LocalAddr())

        // Handle connections in a new goroutine.
        go handleRequest(conn)
    }
}

// Handles incoming requests.
func handleRequest(conn net.Conn) {
    // Make a buffer to hold 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())
    }
    // Builds the message.
    message := "Hi, I received your message! It was "
    message += strconv.Itoa(reqLen)
    message += " bytes long and that's what it said: \""
    n := bytes.Index(buf, []byte{0})
    message += string(buf[:n-1])
    message += "\" ! Honestly I have no clue about what to do with your messages, so Bye Bye!\n"

    // Write the message in the connection channel.
    conn.Write([]byte(message))
    // Close the connection when you're done with it.
    conn.Close()
}

在终端运行:

echo -n "test out the server" | nc localhost 3333

就会看到

Hi, I received your message! It was 19 bytes long and that's what it said: "test out the serve" ! Honestly I have no clue about what to do with your messages, so Bye Bye!

原文 https://coderwall.com/p/wohavg/creating-a-simple-tcp-server-in-go

本文网址: https://golangnote.com/topic/54.html (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。如果你有任何问题可以在下面 留言
Be the first to comment!
Captcha image