下面是一个用Go语言编写的TCPS服务程序,它监听传入的地址和端口,打印连接的客户端信息,并为每个客户端连接创建一个协程来处理客户端的消息。如果在2秒内收不到客户端的消息,它会打印接收超时的消息,但不会断开连接。

package main

import (
	"bufio"
	"fmt"
	"net"
	"time"
)

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

	// 打印客户端信息
	fmt.Printf("New client connected: %s\n", conn.RemoteAddr().String())

	// 设置超时时间为2秒
	conn.SetReadDeadline(time.Now().Add(2 * time.Second))

	for {
		// 读取客户端消息
		message, err := bufio.NewReader(conn).ReadString('\n')
		if err != nil {
			// 判断是否发生超时错误
			if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
				fmt.Println("Receive timeout")
			} else {
				fmt.Println("Error reading message:", err.Error())
			}
			break
		}
		// 打印客户端消息内容
		fmt.Printf("Received message from client: %s", message)
	}
}

func main() {
	// 监听地址和端口
	listener, err := net.Listen("tcp", "127.0.0.1:8080")
	if err != nil {
		fmt.Println("Error listening:", err.Error())
		return
	}
	defer listener.Close()

	fmt.Println("Server started. Waiting for clients...")

	for {
		// 接受客户端连接
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("Error accepting connection:", err.Error())
			return
		}

		// 创建协程处理客户端消息
		go handleClient(conn)
	}
}

在这个例子中,我们使用net.Listen("tcp", "127.0.0.1:8080")函数来监听传入的地址和端口,并使用listener.Accept()函数来接受客户端连接。对于每个客户端连接,我们创建一个协程来处理客户端消息,通过bufio.NewReader(conn).ReadString('\n')函数读取客户端的消息,并使用fmt.Printf()函数打印消息内容。

我们还使用conn.SetReadDeadline(time.Now().Add(2 * time.Second))设置读取超时时间为2秒。如果在2秒内没有收到客户端的消息,将发生一个超时错误,在错误处理代码中打印接收超时的消息。

handleClient()函数中,我们使用defer conn.Close()来确保在函数退出时关闭客户端连接

用go语言写一个TCPS的服务程序监听传入的地址、端口有新的client连接后打印client信息并创建个协程来处理client消息如果收到client的消息则打印消息内容如果超过2S收不到client消息则打印接收超时但是超时后不要断开连接

原文地址: http://www.cveoy.top/t/topic/iYRu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录