-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: connection engine
- Loading branch information
Showing
7 changed files
with
277 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
name: Lint | ||
on: [push, pull_request] | ||
jobs: | ||
golangci: | ||
name: lint | ||
runs-on: ubuntu-latest | ||
steps: | ||
- uses: actions/setup-go@v3 | ||
with: | ||
go-version: 1.18 | ||
- uses: actions/checkout@v3 | ||
- name: golangci-lint | ||
uses: golangci/golangci-lint-action@v3 | ||
with: | ||
version: v1.48 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
on: [push, pull_request] | ||
name: Tests | ||
jobs: | ||
test: | ||
runs-on: ubuntu-latest | ||
steps: | ||
- name: Install Go. | ||
uses: actions/setup-go@v2 | ||
with: | ||
go-version: 1.18 | ||
- name: Checkout code. | ||
uses: actions/checkout@v2 | ||
- name: Run tests. | ||
run: go test -v ./... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
package main | ||
|
||
import ( | ||
"bufio" | ||
"flag" | ||
"fmt" | ||
"log" | ||
"net/url" | ||
"os" | ||
|
||
"github.com/fatih/color" | ||
"github.com/gorilla/websocket" | ||
) | ||
|
||
type ConnReader interface { | ||
ReadJSON(v interface{}) error | ||
} | ||
|
||
type ConnWriter interface { | ||
WriteJSON(v interface{}) error | ||
Close() error | ||
} | ||
|
||
type Scanner interface { | ||
Scan() bool | ||
Text() string | ||
} | ||
|
||
type message struct { | ||
Username string `json:"username"` | ||
Text string `json:"text"` | ||
Type string `json:"type"` | ||
} | ||
|
||
func main() { | ||
var name string | ||
var s *bufio.Scanner | ||
|
||
// Parse flags. | ||
server := flag.String("server", "localhost:9000", "Server network address") | ||
path := flag.String("path", "/", "Server path") | ||
flag.Parse() | ||
|
||
// Construct WebSocket URL. | ||
u := url.URL{Scheme: "ws", Host: *server, Path: *path} | ||
|
||
// Read username. | ||
fmt.Printf("%s", color.YellowString("Enter your Name: ")) | ||
s = bufio.NewScanner(os.Stdin) | ||
s.Scan() | ||
name = s.Text() | ||
|
||
// Display welcome message. | ||
color.Green("\nWelcome %s!\n", name) | ||
color.Green("Connecting to server @ %s\n", *server) | ||
color.Yellow("Send a message, or type !q to exit.\n") | ||
|
||
// Get WebSocket connection. | ||
conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil) | ||
if err != nil { | ||
color.Red("Connection error, exiting: %s", err) | ||
os.Exit(0) | ||
} | ||
defer conn.Close() | ||
|
||
// Send joining message. | ||
msg := message{Username: name, Text: "has joined the chat.", Type: "info"} | ||
_ = conn.WriteJSON(msg) | ||
|
||
go readMessages(conn) // Handle incoming messages concurrently. | ||
writeMessages(conn, s, name) // Handle outgoing messages concurrently. | ||
} | ||
|
||
// readMessages handles incoming messages on the WebSocket connection. | ||
func readMessages(conn ConnReader) { | ||
for { | ||
var msg message | ||
|
||
// Read message. | ||
err := conn.ReadJSON(&msg) | ||
if err != nil { | ||
color.Red("Server closed. Exiting...") | ||
os.Exit(0) | ||
} | ||
|
||
// Display message. | ||
color.Magenta("%s: %s\n", msg.Username, msg.Text) | ||
} | ||
} | ||
|
||
// writeMessages scans stdin and sends each scanned line to the server as JSON. | ||
func writeMessages(conn ConnWriter, s Scanner, name string) { | ||
var msg message | ||
msg.Username = name | ||
|
||
for { | ||
fmt.Print("> ") | ||
if s.Scan() { | ||
fmt.Printf("\033[A") | ||
msg.Text = s.Text() | ||
|
||
// Handle quit event. | ||
if msg.Text == "!q" { | ||
fmt.Println("Goodbye!") | ||
_ = conn.WriteJSON(message{Username: name, Text: "has disconnected.", Type: "info"}) | ||
conn.Close() | ||
os.Exit(0) | ||
} | ||
|
||
// Display message. | ||
if msg.Type != "" { | ||
color.Cyan("%s %s\n", msg.Username, msg.Text) | ||
} else { | ||
color.Cyan("%s: %s\n", msg.Username, msg.Text) | ||
} | ||
|
||
// Write message to connection. | ||
err := conn.WriteJSON(msg) | ||
if err != nil { | ||
log.Fatal("Error sending message, exiting") | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
package main | ||
|
||
import ( | ||
"flag" | ||
"log" | ||
"net/http" | ||
"time" | ||
|
||
"github.com/fatih/color" | ||
"github.com/google/uuid" | ||
"github.com/gorilla/websocket" | ||
) | ||
|
||
type message struct { | ||
Username string `json:"username"` | ||
Text string `json:"text"` | ||
Type string `json:"type"` | ||
ID uuid.UUID | ||
} | ||
|
||
// Upgrader instance to upgrade all HTTP connections to a WebSocket. | ||
var upgrader = websocket.Upgrader{} | ||
|
||
// Map to store currently active client connections. | ||
var activeClients = make(map[*websocket.Conn]uuid.UUID) | ||
|
||
// Channel for client messages. | ||
var messageChan = make(chan message) | ||
|
||
func main() { | ||
// Parse flags. | ||
addr := flag.String("addr", ":9000", "Server's network address") | ||
flag.Parse() | ||
|
||
mux := http.NewServeMux() | ||
mux.HandleFunc("/", handleConn) | ||
|
||
// Handle incoming messages. | ||
go handleMsg() | ||
|
||
// Start the server. | ||
log.Printf("Starting server on %s", *addr) | ||
err := http.ListenAndServe(*addr, mux) | ||
if err != nil { | ||
log.Fatal("Error starting server, exiting.", err) | ||
} | ||
} | ||
|
||
// handleConn handles incoming HTTP connections by adding the connection to activeClients and reads messages from the connection. | ||
func handleConn(w http.ResponseWriter, r *http.Request) { | ||
// Upgrade incoming HTTP connections to WebSocket connections | ||
conn, err := upgrader.Upgrade(w, r, nil) | ||
if err != nil { | ||
log.Printf("Error upgrading connection to websocket: %v", err) | ||
} | ||
defer conn.Close() | ||
|
||
// Generate a UUID for the client. | ||
activeClients[conn] = uuid.New() | ||
|
||
for { | ||
var msg message | ||
|
||
// Read message from the connection. | ||
err := conn.ReadJSON(&msg) | ||
if err != nil { | ||
log.Printf("Closing connection with ID: %v", activeClients[conn]) | ||
delete(activeClients, conn) | ||
break | ||
} | ||
|
||
// Set message ID | ||
msg.ID = activeClients[conn] | ||
|
||
// Send message to messageChan. | ||
messageChan <- msg | ||
} | ||
} | ||
|
||
// handleMsg listens to the messageChan channel and broadcasts messages to other clients. | ||
func handleMsg() { | ||
for { | ||
// Get message from messageChan. | ||
msg := <-messageChan | ||
|
||
// Log each message to stdout. | ||
t := time.Now().Format(time.ANSIC) | ||
if msg.Type != "" { | ||
color.Green("%s >> %s %s\n", t, msg.Username, msg.Text) | ||
} else { | ||
color.Green("%s >> %s: %s\n", t, msg.Username, msg.Text) | ||
} | ||
|
||
// Broadcast to all active clients. | ||
for client, UUID := range activeClients { | ||
// Check the UUID to prevent sending messages to their origin. | ||
if msg.ID != UUID { | ||
// Write JSON message. | ||
err := client.WriteJSON(msg) | ||
if err != nil { | ||
log.Printf("Error sending message to client: %v", err) | ||
client.Close() | ||
delete(activeClients, client) | ||
} | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters