Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "bufio"
- "fmt"
- "log"
- "math/rand"
- "net"
- "os"
- "time"
- )
- func main() {
- connHost := "localhost"
- connPort := "9090"
- l, err := net.Listen("tcp", connHost+":"+connPort)
- if err != nil {
- log.Println("Error listening:", err.Error())
- os.Exit(1)
- }
- fmt.Println("TCP listening")
- for {
- conn, err := l.Accept()
- if err != nil {
- log.Println("Error accepting: ", err.Error())
- os.Exit(1)
- }
- go readMessage(conn) // ทำให้เป็น goroutine
- }
- }
- func readMessage(conn net.Conn) {
- timeoutDuration := 10 * time.Second
- conn.SetReadDeadline(time.Now().Add(timeoutDuration))
- message, err := bufio.NewReader(conn).ReadString('\n')
- if err != nil {
- log.Println("Error rea dmessage: ", err.Error())
- conn.Write([]byte("\n"))
- return
- }
- time.Sleep(100 * time.Duration(rand.Intn(10)) * time.Millisecond) // เพิ่ม delay ให้แต่ละ message ใช้เวลาไม่เท่ากัน
- conn.Write([]byte("server received message\n"))
- fmt.Println("Message : ", message)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement