2023-03-05 03:57:27 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net"
|
|
|
|
)
|
|
|
|
|
2023-03-05 08:14:36 +00:00
|
|
|
type Server struct {
|
|
|
|
listener net.Listener
|
|
|
|
clients map[*Client]bool
|
|
|
|
unregister chan *Client
|
2023-03-05 03:57:27 +00:00
|
|
|
}
|
|
|
|
|
2023-03-05 08:14:36 +00:00
|
|
|
func newServer() *Server {
|
|
|
|
listener, err := net.Listen("tcp", ":23000")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
2023-03-05 03:57:27 +00:00
|
|
|
}
|
|
|
|
|
2023-03-05 08:14:36 +00:00
|
|
|
return &Server{
|
|
|
|
listener: listener,
|
|
|
|
clients: make(map[*Client]bool),
|
|
|
|
unregister: make(chan *Client),
|
|
|
|
}
|
2023-03-05 03:57:27 +00:00
|
|
|
}
|
|
|
|
|
2023-03-05 08:14:36 +00:00
|
|
|
func (server *Server) Start() {
|
|
|
|
log.Print("Server hosted on 127.0.0.1:23000")
|
2023-03-05 03:57:27 +00:00
|
|
|
|
|
|
|
for {
|
2023-03-05 08:14:36 +00:00
|
|
|
select {
|
|
|
|
case client := <-server.unregister:
|
|
|
|
delete(server.clients, client)
|
|
|
|
fmt.Printf("Client %p disconnected\n", client)
|
2023-03-05 03:57:27 +00:00
|
|
|
default:
|
2023-03-05 08:14:36 +00:00
|
|
|
conn, err := server.listener.Accept()
|
|
|
|
if err != nil {
|
|
|
|
log.Println("Connection error: ", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-03-07 07:20:36 +00:00
|
|
|
client := newClient(server, conn)
|
2023-03-05 08:14:36 +00:00
|
|
|
server.clients[client] = true
|
|
|
|
go client.ClientHandler()
|
|
|
|
fmt.Printf("Client %p connected\n", client)
|
2023-03-05 03:57:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2023-03-05 08:14:36 +00:00
|
|
|
server := newServer()
|
|
|
|
server.Start()
|
2023-03-05 03:57:27 +00:00
|
|
|
}
|