golang socket

server.go

package main

import (
    "fmt"
    "log"
    "net"
    "time"
)

func handle(conn net.Conn) {
    defer conn.Close()

    ip := conn.RemoteAddr().String()
    fmt.Printf("%s 客户端【%s】连接成功\n", time.Now().Format("2006/01/02 15:04:05"), ip)

    for {
        message := make([]byte, 1024)
        n, err := conn.Read(message)
        if err != nil {
            fmt.Printf("%s 客户端【%s】退出连接\n", time.Now().Format("2006/01/02 15:04:05"), ip)
            return
        }
        fmt.Printf("%s 客户端【%s】发来消息:%s\n", time.Now().Format("2006/01/02 15:04:05"), ip, message[:n])
    }
}

func main() {
    listen, err := net.Listen("tcp", ":8888")
    if err != nil {
        log.Fatal("监听端口发生错误,err=", err)
    }
    defer listen.Close()

    for {
        conn, err := listen.Accept()
        if err != nil {
            log.Println("客户端连接发生错误,err=", err)
            continue
        }
        handle(conn)
    }
}

client.go

package main

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

func main() {
    conn, err := net.Dial("tcp", "127.0.0.1:8888")
    if err != nil {
        log.Fatal("连接服务端错误,err=", err)
    }
    defer conn.Close()

    reader := bufio.NewReader(os.Stdin)
    for {
        fmt.Print("请输入消息:")
        line, err := reader.ReadString('\n')
        if err != nil {
            log.Println("读取输入发生错误,err=", err)
            return
        }
        if strings.Trim(line, "\r\n") == "exit" {
            fmt.Println("客户端退出")
            return
        }
        _, err = conn.Write([]byte(line))
        if err != nil {
            log.Println("发送消息错误,err=", err)
            return
        }
    }
}