golang TCP服务器与客户端Hello world

内容目录

概述

golang是一个简单语言,当然它支持网络编程,golang网络编程主要使用https://pkg.go.dev/net。它提供了简单的网络编程API,不过需要注意:

链接中的有些功能特性是没有实现的

今天我们用go实现一个helloworld TCP Server和Client。

Server


package main

import (
    "io"
    "log"
    // 引入net包
    "net"
    "fmt"
)

func main() {
    // 监听本地端口14141
    addr := "localhost:14141"
    server, err := net.Listen("tcp", addr)
    if err != nil {
        log.Fatalln(err)
    }
    defer server.Close()

    log.Println("Server is running on:", addr)

    for {
        // 准备接收连接
        conn, err := server.Accept()
        if err != nil {
            log.Println("Failed to accept conn.", err)
            continue
        }

        // 异步处理请求
        go HandleRequest(conn)
    }
}

func HandleRequest(conn net.Conn) {
    defer conn.Close()
    b := make([]byte, 512)
    // 读取客户端数据
    size, err := conn.Read(b)
    if err == io.EOF {
        log.Println("Closed connection.")
    }
    if err != nil {
        log.Fatal(err)
    }

    // 从写入数据到客户端
    fmt.Printf("Received %v bytes", size)
    size, err = conn.Write(b[0:size])
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Written %v bytes", size)
}

Client


package main

import(
    "fmt"
    "os"
    "net"
)

func main() {
    // 本地端口
    localAddr, err := net.ResolveTCPAddr("tcp", "localhost:14142")
    ExitOnError(err)

    // 远程端口
    address := "localhost:14141"
    remoteAddr, err := net.ResolveTCPAddr("tcp", address)
    ExitOnError(err)

    // 连接TCP服务器
    conn, err := net.DialTCP("tcp", localAddr, remoteAddr)
    ExitOnError(err)

    // 主动发送Hello World数据
    Ping(conn, "Hello world!")
}

func Ping(conn net.Conn, msg string) {

    // 将字符串转换为byte数组,网络发送得用字节流
    _, err := conn.Write([]byte(msg))
    ExitOnError(err)

    fmt.Println("Sent", msg)

    // 从服务器端读取字节流
    buf := make([]byte, 512)
    _, err = conn.Read(buf)
    ExitOnError(err)

    // 字节流转换为字符串
    fmt.Println("Got ", string(buf))
}

func ExitOnError(err error) {
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

测试

编译客户端和服务端

go build helloserver.go
go build helloclient.go

执行两个可执行文件

./helloserver.exe

./helloclient.exe

运行结果

Server端

 .\helloserver.exe
2024/01/31 21:42:18 Server is running on: localhost:14141
Received 12 bytesWritten 12 bytes

客户端

.\helloclient.exe
Sent Hello world!
Got  Hello world!

5人评论了“golang TCP服务器与客户端Hello world”

  1. Woah! I’m really loving the template/theme of this website.
    It’s simple, yet effective. A lot of times it’s hard to get that “perfect balance” between usability and visual
    appeal. I must say you’ve done a great job with this. Also, the blog loads super fast for me on Chrome.
    Excellent Blog!

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部