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

Posted 卑微的小李

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 从入门到放弃

 

以上是关于Golang TCP服务器监听用户上下线的主要内容,如果未能解决你的问题,请参考以下文章

Golang 从入门到放弃

Golang 从入门到放弃

Golang TCP监听服务器搭建

Golang TCP监听服务器搭建

Zookeeper实战监听服务器节点动态上下线案例

Hadoop基础(三十六):监听服务器节点动态上下线案例