使用go实现一个简单的聊天服务器,对于客户端发送的消息,服务端添加时间戳和冒号后返回客户端。
1. 代码
import (
"bufio"
"fmt"
"net"
"strings"
"time"
)
func handleConnection(conn net.Conn) {
defer conn.Close()
fmt.Println("Client connected:", conn.RemoteAddr())
reader := bufio.NewReader(conn)
for {
// 读取客户端消息
message, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Client disconnected:", conn.RemoteAddr())
return
}
// 添加时间戳
timestamp := time.Now().Format("2006-01-02 15:04:05")
response := fmt.Sprintf("%s: %s", timestamp, strings.TrimSpace(message))
// 返回处理后的消息
conn.Write([]byte(response + "\n"))
}
}
func main() {
// 监听 TCP 连接
ln, err := net.Listen("tcp", ":8090")
if err != nil {
fmt.Println("Error listening:", err)
return
}
defer ln.Close()
fmt.Println("Server started on :8090")
for {
// 接受客户端连接
conn, err := ln.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
continue
}
// 处理客户端连接
go handleConnection(conn)
}
}
2. 导出二进制包
# 打包x86部署包
GOARCH=amd64 GOOS=linux go build -o gochat main.go
# 打包arm部署包
GOARCH=arm64 GOOS=linux go build -o gochat main.go
3. 构建成镜像
Dockerfile:
# Build the stellaris-core binary
FROM alpine:3.11
WORKDIR /workspace
# Copy the go source
COPY gochat /gochat
# Build
ENTRYPOINT ["/gochat"]
build.sh:
docker build -t gochat:v1 . -f Dockerfile
start.sh
docker run --name gochat -d -p 8090:8090 docker.io/library/gochat:v1
4. 使用telnet测试
telnet localhost 8089
send hello