Golang TCP服务器监听用户上下线

main.go:

package main

import "fmt"

func main()  {
	server := NewServer("127.0.0.1",8888)
	if !server.Start() {
		fmt.Println("服务器启动失败")
		return
	}

}

server.go:

监听线程发现新连接时,把每个连接记录到map中(用锁保证数据安全),当有新连接过来时则通知已存在的连接。

package main

import (
	"fmt"
	"net"
	"sync"
)

type Server struct {
	Ip string
	Port int

	users map[string]*User
	userMutex sync.RWMutex
	msgC chan string
}

func NewServer(ip string,port int) *Server  {
	server := &Server{
		Ip: ip,
		Port: port,
		users: make(map[string]*User),
		msgC: make(chan string),
	}
	return server
}

func (this *Server) handler(conn net.Conn)  {
	fmt.Println(fmt.Sprintf("%s: 连接成功",conn.RemoteAddr().String()))
	this.userMutex.Lock()
	this.users[conn.RemoteAddr().String()] = NewUser(conn,this)
	this.userMutex.Unlock()
}

func (this *Server) Start() bool {
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d",this.Ip,this.Port))
	defer listener.Close()

	if err != nil {
		fmt.Println("net listen err:",err)
		return false
	}

	go this.listenMsg()

	for  {
		con, err := listener.Accept()
		if err != nil {
			fmt.Println("net Accept err:",err)
			continue
		}
		this.userOnline(con.RemoteAddr().String())
		go this.handler(con)
	}

	return true
}

func (this *Server) listenMsg()  {
	for  {
		msg:= <- this.msgC
		this.brodCast([]byte(msg))
	}
}

func (this *Server) brodCast(msg []byte )  {
	this.userMutex.Lock()
	for _, v := range this.users {
		_,err := v.Conn.Write(msg)
		if err != nil {
			fmt.Println("server brodCast err:",err)
		}
	}
	this.userMutex.Unlock()
}

func (this *Server) userOnline(name string)  {
	this.userMutex.Lock()
	for _, v := range this.users {
		_,err := v.Conn.Write([]byte(fmt.Sprintf("user:%s online",name)))
		if err != nil {
			fmt.Println("server brodCast err:",err)
		}
	}
	this.userMutex.Unlock()
}

func (this *Server) userOffline(ip string)  {
	this.userMutex.Lock()
	username := this.users[ip].Name
	delete(this.users, ip)
	this.userMutex.Unlock()
	this.brodCast([]byte(fmt.Sprintf("user:%s offline.",username)))
}

 

user.go:

建立对象时同时创建协程阻塞读取数据,当不再阻塞同时数据大小为0时,连接断开。

package main

import (
	"fmt"
	"net"
	"runtime"
)

type User struct {
	Name string
	Address string
	C chan string
	Conn net.Conn
	server *Server
}

func NewUser(conn net.Conn,ser *Server) *User  {
	user := &User{
		Name: conn.RemoteAddr().String(),
		Address: conn.RemoteAddr().String(),
		C: make(chan string),
		Conn: conn,
		server: ser,
	}

	go user.listenMessage()

	return user
}

func (this *User) listenMessage()  {

	for  {
			msg :=make([]byte,4096)
			num,err :=this.Conn.Read(msg)
			if err != nil {
				fmt.Println("user Read err:",err)
			}
			if num==0 {
				fmt.Println(fmt.Sprintf("user:%s device offline.",this.Conn.RemoteAddr().String()))
				this.server.userOffline(this.Conn.RemoteAddr().String())
				_ = this.Conn.Close()
				close(this.C)
				runtime.Goexit()
			}
	}
}

 

 

 

目录:

Golang 从入门到放弃

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值