main.go
package main
func main(){
server := NewServer("1.1.1.1",10830)
server.Start()
}
server.go
package main
import (
"fmt"
"io"
"net"
"sync"
)
type Server struct {
Ip string
Port int
UserMap map[string]*User
maplock sync.RWMutex
C chan string
}
func NewServer(ip string,port int) *Server {
server := &Server{
Ip:ip,
Port: port,
UserMap: make(map[string]*User),
C: make(chan string),
}
return server
}
func (this *Server) UserWriteC(user *User,msg string){
msg2 := "["+user.UserName+"]:"+msg
this.C <- msg2
}
func (this *Server) GuangBo(){
for {
msg := <-this.C
this.maplock.Lock()
for _, u := range this.UserMap {
u.C <- msg
}
this.maplock.Unlock()
}
}
func (this *Server) Handler(conn net.Conn){
fmt.Println("Hello,",conn.RemoteAddr().String())
conn.Write([]byte("登陆成功!\n"))
user := NewUser(conn)
this.maplock.Lock()
this.UserMap[user.UserName]=user
this.maplock.Unlock()
this.UserWriteC(user,"已上线")
go func(){
buf:=make([]byte,4096)
for {
n,err := conn.Read(buf)
if n==0{
this.UserWriteC(user,"下线")
return
}
if err!=nil && err!=io.EOF{
fmt.Println("conn.Read(buf) err: ",err)
return
}
msg := string(buf[:n-1])
this.UserWriteC(user,msg)
}
}()
select {
}
}
func (this *Server) Start() {
listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", this.Ip, this.Port))
if err != nil {
fmt.Println("net.Listen err: ", err)
}
defer listener.Close()
go this.GuangBo()
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("listener.Accept() err: ", err)
continue
}
go this.Handler(conn)
}
}
user.go
package main
import (
"net"
)
type User struct {
UserName string
UserAddr string
C chan string
Conn net.Conn
}
func NewUser(conn net.Conn) *User{
var user User
user.UserName=conn.RemoteAddr().String()
user.UserAddr=conn.RemoteAddr().String()
user.C = make(chan string)
user.Conn = conn
go user.UserReadmsg()
return &user
}
func (user *User) UserReadmsg() {
for {
msg := <-user.C
user.Conn.Write([]byte(msg + "\n"))
}
}
|