《GO程序设计语言》设计中案例,仅作为笔记进行收藏。简单的聊天服务器,使用telnet 发送信息。

package main

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

func main() {
	listener, err := net.Listen("tcp", "localhost:8000")
	if err != nil {
		log.Fatal(err)
	}

	go broadcaster()

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Print(err)
			continue
		}

		go handleConn(conn)
	}
}

// 对外发送消息的通道
type client chan<- string

var (
	entering = make(chan client)
	leaving  = make(chan client)
	// 所有接收的客户消息
	messages = make(chan string)
)

func broadcaster() {
	// 所有链接的客户端
	clients := make(map[client]bool)
	for {
		select {
		case msg := <-messages:
			// 把所有接收的消息广播给所有的客户
			// 发送消息通道
			for cli := range clients {
				cli <- msg
			}

		case cli := <-entering:
			clients[cli] = true

		case cli := <-leaving:
			delete(clients, cli)
			close(cli)
		}
	}
}

// 创建一个对外发送消息的新通道
func handleConn(conn net.Conn) {
	// 对外发送消息的通道
	ch := make(chan string)
	go clientWriter(conn, ch)

	who := conn.RemoteAddr().String()
	ch <- "You are " + who
	messages <- who + " has arrived"
	entering <- ch

	input := bufio.NewScanner(conn)
	for input.Scan() {
		// 注意,忽略 input.Err() 中可能的错误
		messages <- who + ": " + input.Text()
	}

	leaving <- ch
	messages <- who + " has left"
	conn.Close()
}

func clientWriter(conn net.Conn, ch <-chan string) {
	for msg := range ch {
		// 注意,忽略网络层面的错误
		fmt.Fprintln(conn, msg)
	}
}