gopenfusion/server/server.go

57 lines
1009 B
Go
Raw Normal View History

package main
import (
"fmt"
"log"
"net"
2023-03-07 00:39:41 +00:00
"github.com/CPunch/GopenFusion/protocol"
)
2023-03-05 08:14:36 +00:00
type Server struct {
listener net.Listener
clients map[*Client]bool
unregister chan *Client
}
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 08:14:36 +00:00
return &Server{
listener: listener,
clients: make(map[*Client]bool),
unregister: make(chan *Client),
}
}
2023-03-05 08:14:36 +00:00
func (server *Server) Start() {
log.Print("Server hosted on 127.0.0.1:23000")
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)
default:
2023-03-05 08:14:36 +00:00
conn, err := server.listener.Accept()
if err != nil {
log.Println("Connection error: ", err)
return
}
client := newClient(server, conn, []byte(protocol.E_KEY))
server.clients[client] = true
go client.ClientHandler()
fmt.Printf("Client %p connected\n", client)
}
}
}
func main() {
2023-03-05 08:14:36 +00:00
server := newServer()
server.Start()
}