聊天系统-服务器端

聊天系统-服务器端

package main

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

func main() {
	port := "9090"
	StartServer(port)
}

//启动服务器
func StartServer(port string) {
	host := ":" + port
	//获取tcp地址
	tcpAddr, err := net.ResolveTCPAddr("tcp4", host)
	if err != nil {
		log.Printf("resolve tcp addr failed:%v/n", err)
		return
	}

	//监听
	listener, err := net.ListenTCP("tcp", tcpAddr)
	if err != nil {
		log.Printf("Listen tcp port failed:%v\n", err)
		return
	}

	//建立链接池,用于广播消息
	conns := make(map[string]net.Conn)
	//消息通道
	messageChan := make(chan string, 10)

	//广播消息
	BroadMessage(&conns, messageChan)

	//启动
	for {
		fmt.Printf("listening port %s ...\n", port)
		conn, err := listener.AcceptTCP()
		if err != nil {
			log.Printf("Accept failed:%v\n", err)
			continue
		}
		//把每个客户端链接扔进链接池
		conns[conn.RemoteAddr().String()] = conn
		fmt.Println(conns)
		//处理消息
		Handler(conn, &conns, messageChan)

	}
}
func Handler(conn net.Conn, conns *map[string]net.Conn, messages chan string) {
	buf := make([]byte, 1024)
	for {
		length, err := conn.Read(buf)
		if err != nil {
			log.Printf("read client message failed:%v\n", err)
			delete(*conns, conn.RemoteAddr().String())
			conn.Close()
			break
		}
		//把收到的消息写到通道中
		recvStr := string(buf[0:length])
		messages <- recvStr
	}
}

//向所有链接上的发消息
func BroadMessage(conns *map[string]net.Conn, messages chan string) {
	for {
		//不断从通道里读取消息
		msg := <-messages
		fmt.Println(msg)
		//向所有的人发消息
		for key, conn := range *conns {
			_, err := conn.Write([]byte(msg))
			if err != nil {
				log.Printf("broad message to %s failed:%v\n", key, err)
				delete(*conns, key)
			}
		}
	}
}

你可能感兴趣的:(go,聊天系统)