-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket_handler.go
80 lines (66 loc) · 1.68 KB
/
socket_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
// This is intended to be used between multiple instances of the keystore, and will allow for redundant replication.
// ** Still a work in progress - Asymmetric Encryption needs to be in place before this can occur.
import (
"net"
"fmt"
)
type SocketAuth struct {
Username string
Token []byte
}
type SocketMessage struct {
Auth SocketAuth
Message []byte
}
// As a server, listen for incoming connections
func startServer() {
// Listen for incoming connections on port 8080
ln, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println(err)
return
}
// Accept incoming connections and handle them
for {
conn, err := ln.Accept()
if err != nil {
fmt.Println(err)
continue
}
// Handle the connection in a new goroutine
go handleConnection(conn)
}
}
// As a server, handle a connection
func handleConnection(connection net.Conn) {
// Close the connection when we're done
defer connection.Close()
// Read incoming data
buf := make([]byte, 1024)
_, err := connection.Read(buf)
if err != nil {
fmt.Println(err)
return
}
// Print the incoming data
fmt.Printf("Received: %s", buf)
}
// As a client, create a connection
func createConnection() {
// Connect to the server
conn, err := net.Dial("tcp", "localhost:8080")
if err != nil {
fmt.Println(err)
return
}
// Send some data to the server
_, err = conn.Write([]byte("Hello, server!"))
if err != nil {
fmt.Println(err)
return
}
// Close the connection
defer conn.Close()
}
func closeConnection() {}