golang实现聊天后台服务器

//功能简介
/*
1.广播功能, 用户上线下线 广播所有在线用户 某某用户下线
2.改名功能 输入rename|newname 可以更改自己的昵称
3.查看当前在线用户功能 输入who 可列表当前在线用户
4.聊天功能, 任一连接成员, 发送消息, 广播所有用户, 类似于群聊
5.超时自动退出
*/
 
package main
 
import (
	"fmt"
	"net"
	"strings"
	"time"
)
 
// 线上用户结构体
type Client struct {
     
	C    chan string //通信,发送数据对当前用户
	Name string
	Addr string
}
 
func clientHandler(conn net.Conn) {
     
	defer conn.Close()
	// 加入到在线用户列表中
	remoteAddr := conn.RemoteAddr().String()
	client := Client{
     make(chan string), "phpxxo", remoteAddr}
	onlieMap[remoteAddr] = client
 
	//向当前用户发送消息
	go writeMsgToClient(client, conn)
	//广播用户上线
	message <- makeMsg(client, "login success")
	conn.Write([]byte(makeMsg(client, "i am here")))
 
	clientExit := make(chan bool)
	hasData := make(chan bool)
	//监听用户消息
	go func() {
     
		buf := make([]byte, 1024)
		for {
     
			n, err := conn.Read(buf)
			if n == 0 {
     
				clientExit <- true
				fmt.Println("conn.Read err:", err)
				return
			}
			msg := string(buf[:n-1])
			if msg == "who" {
     
				conn.Write([]byte("user list:\n"))
				for _, cli := range onlieMap {
     
					conn.Write([]byte(cli.Addr + ":" + cli.Name + "\n"))
				}
			} else if len(msg) >= 6 && msg[:6] == "rename" {
     
				name := strings.Split(msg, "|")[1]
				client.Name = name
				onlieMap[client.Addr] = client
				conn.Write([]byte("rename success\n"))
			} else {
     
				message <- makeMsg(client, msg)
			}
			hasData <- true
		}
	}()
 
	timer := time.NewTimer(time.Second * 30)
	for {
     
		select {
     
		case <-clientExit:
			delete(onlieMap, client.Addr)
			message <- makeMsg(client, "login out")
			return
		case <-hasData:
			timer.Reset(time.Second * 30)
		case <-timer.C:
			delete(onlieMap, client.Addr)
			message <- makeMsg(client, "time out login out")
			return
 
		}
 
	}
}
 
var message chan string = make(chan string) // 转发的消息
var onlieMap map[string]Client              //在线用户
// 组装消息
func makeMsg(client Client, msg string) string {
     
	return "[" + client.Addr + "]" + client.Name + ":" + msg + "\r\n"
}
 
// 发送消息给客户端
func writeMsgToClient(client Client, conn net.Conn) {
     
	for msg := range client.C {
     
		_, err := conn.Write([]byte(msg))
		if err != nil {
     
			fmt.Println("writeMsgToClient err:", err)
		}
 
	}
}
 
// 广播消息
func manage() {
     
	onlieMap = make(map[string]Client)
	for {
     
		msg := <-message
		for _, client := range onlieMap {
     
			client.C <- msg
		}
	}
 
}
 
func main() {
     
	listen, err := net.Listen("tcp", "127.0.0.1:8080")
	if err != nil {
     
		fmt.Println("listen err:", err)
		return
	}
	defer listen.Close()
	go manage() //监听用户消息, 转发
 
	for {
     
		conn, err := listen.Accept()
		if err != nil {
     
			fmt.Println("accept err:", err)
			continue
		}
 
		// 用户处理
		go clientHandler(conn)
 
	}
 
}

你可能感兴趣的:(golang,websocket,聊天室,golang)