sshpong/internal/netwrk/netwrk.go

95 lines
1.6 KiB
Go
Raw Normal View History

2024-08-02 13:04:41 -06:00
package netwrk
import (
"log"
"net"
2024-08-15 20:08:23 -06:00
sync "sync"
2024-08-23 11:59:19 -06:00
"google.golang.org/protobuf/proto"
2024-08-02 13:04:41 -06:00
)
type Client struct {
2024-08-15 20:08:23 -06:00
Username string
Conn net.Conn
2024-08-02 13:04:41 -06:00
}
2024-08-15 20:08:23 -06:00
type LobbyPlayersMessage struct {
Type string
Username string
IsAvailable chan bool
2024-08-02 13:04:41 -06:00
}
2024-08-15 20:08:23 -06:00
type ExternalMessage struct {
Target string
Message *LobbyMessage
2024-08-02 13:04:41 -06:00
}
2024-08-15 20:08:23 -06:00
var lobbyListener chan LobbyPlayersMessage
var externalMessageChan chan ExternalMessage
var lobbyMembers sync.Map
func init() {
lobbyListener = make(chan LobbyPlayersMessage)
externalMessageChan = make(chan ExternalMessage)
2024-08-02 13:04:41 -06:00
2024-08-15 20:08:23 -06:00
lobbyMembers = sync.Map{}
2024-08-23 11:59:19 -06:00
go func() {
for {
msg := <-externalMessageChan
player, ok := lobbyMembers.Load(msg.Target)
if !ok {
2024-08-24 16:09:12 -06:00
log.Println("failed to send to target", msg.Target)
2024-08-23 11:59:19 -06:00
continue
}
client, _ := player.(Client)
bytes, _ := proto.Marshal(msg.Message)
2024-08-24 16:09:12 -06:00
_, err := client.Conn.Write(bytes)
if err != nil {
log.Println("Could not write to target", msg.Target, err)
}
2024-08-23 11:59:19 -06:00
}
}()
2024-08-15 20:08:23 -06:00
}
2024-08-02 13:04:41 -06:00
2024-08-05 18:00:41 -06:00
// Starts listening on port 12345 for TCP connections
// Also creates client pool and game connection singletons
2024-08-15 20:08:23 -06:00
func LobbyListen() {
2024-08-02 13:04:41 -06:00
2024-08-14 23:33:05 -06:00
listener, err := net.Listen("tcp", "127.0.0.1:12345")
2024-08-02 13:04:41 -06:00
if err != nil {
log.Fatal(err)
}
defer listener.Close()
2024-08-15 20:08:23 -06:00
for {
conn, err := listener.Accept()
if err != nil {
log.Println(err)
continue
2024-08-06 09:58:43 -06:00
}
2024-08-15 20:08:23 -06:00
go handleLobbyConnection(conn)
2024-08-09 08:48:12 -06:00
}
2024-08-15 20:08:23 -06:00
}
func GamesListen() {
2024-08-09 08:48:12 -06:00
2024-08-14 23:33:05 -06:00
gameListener, err := net.Listen("tcp", "127.0.0.1:42069")
2024-08-14 17:26:51 -06:00
if err != nil {
log.Fatal(err)
}
defer gameListener.Close()
2024-08-14 23:33:05 -06:00
for {
conn, err := gameListener.Accept()
if err != nil {
log.Println(err)
continue
2024-08-08 18:08:55 -06:00
}
2024-08-14 23:33:05 -06:00
handleGameConnection(conn)
}
2024-08-06 09:58:43 -06:00
}