Receive connections and add client

This commit is contained in:
cyp0633 2022-11-22 10:04:00 +08:00
commit 1cfb9cd50b
Signed by: cyp0633
GPG Key ID: 8ACC79012E3DDAA0
5 changed files with 82 additions and 0 deletions

22
.gitignore vendored Normal file
View File

@ -0,0 +1,22 @@
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
socket-server
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
# Go workspace file
go.work

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module socket-server
go 1.19

10
internal/client.go Normal file
View File

@ -0,0 +1,10 @@
package internal
import "net"
var Clients map[string]net.Conn
func AddClient(conn net.Conn) {
addr := conn.RemoteAddr().(*net.TCPAddr).IP.String()
Clients[addr] = conn
}

23
internal/tcp.go Normal file
View File

@ -0,0 +1,23 @@
package internal
import (
"log"
"net"
)
func TCPHandler(conn net.Conn) {
defer conn.Close()
for {
var buf = make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
log.Default().Println(err)
return
}
log.Default().Println(string(buf[:n]))
switch msg := string(buf[:n]); {
case msg == "HELO":
}
}
}

24
main.go Normal file
View File

@ -0,0 +1,24 @@
package main
import (
"log"
"net"
"socket-server/internal"
)
func main() {
ln, err := net.Listen("tcp", ":65432")
if err != nil {
log.Fatal(err)
panic(err)
}
for {
conn, err := ln.Accept()
if err != nil {
log.Fatal(err)
panic(err)
}
go internal.TCPHandler(conn)
go internal.AddClient(conn)
}
}