Golang实战-一个聊天室的实现二

在上一篇《Golang实战-一个聊天室的实现》中,我们按照书上写了个简单的聊天室,今天我们来加点我们自己的东西:

可新增房间,并切换房间。

要想新建房间,得有个房间的对象,保存房间的一些基本信息:

type RoomInfo struct {
    Name string `json:"name"`
    //删除房间时用,只有房间创建者可删除
    CreaterId string `json:"creater_id"`
}
房间有了,下面是房间里的人:

type ClientInfo struct {
    Id string  `json:"id"`
    Nickname string `json:"nickname"`
    CurrentRoom RoomInfo `json:"current_room"`
    ClientResource chan<- string
}
房间和人的关系应该是一对多的关系:

type Clients []*ClientInfo
type ChatRoom struct {
    RoomMap map[RoomInfo]Clients
}
房间和人都定义好了,我们需要对房间有一些基本的增、删操作,将它们独立到一个文件db.go里:

package chat

type ClientInfo struct {
    Id string  `json:"id"`
    Nickname string `json:"nickname"`
    CurrentRoom RoomInfo `json:"current_room"`
    ClientResource chan<- string
}

type RoomInfo struct {
    Name string `json:"name"`
    //删除房间时用,只有房间创建者可删除
    CreaterId string `json:"creater_id"`
}

type Clients []*ClientInfo
type RoomList []RoomInfo

type ChatRoom struct {
    RoomMap map[RoomInfo]Clients
}

func NewChatRoom() *ChatRoom {
    return &ChatRoom{
        RoomMap: make(map[RoomInfo]Clients),
    }
}

func (c *ChatRoom) AddRoom(r RoomInfo) {
    //判断房间是否已存在
    _, ok := c.RoomMap[r]
    if !ok {
        c.RoomMap[r] = Clients{}
    }
}

func (c *ChatRoom) AddClient(r RoomInfo, cli *ClientInfo) {
    clients := c.RoomMap[r]
    found := false

    //防止重复添加
    for _, client := range clients {
        if client.Id == cli.Id {
            found = true
        }
    }

    if found == false {
        cli.CurrentRoom = r
        c.RoomMap[r] = append(clients, cli)
    }
}

func (c *ChatRoom) RemoveClient(r RoomInfo, id string) (bool, int) {
    clients, ok :=
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值