This is an example of a WebSocket server written in Go. It utilizes the Gorilla WebSocket library to handle WebSocket connections.
The server has the following features:
- Accepts WebSocket connections on the "/ws" route.
- Allows clients to connect and send messages.
- Maintains a list of connected clients.
- Broadcasts received messages from a client to all other connected clients.
-
Make sure you have Go installed on your system.
-
Download or clone this repository.
-
Open a terminal and navigate to the root directory of the project.
-
Run the following command to start the server:
go run main.go
-
The server will be running on port 8080.
-
Open a web browser and access http://localhost:8080.
-
The web client will display a page with a text input field.
-
Open multiple browser tabs or windows to simulate multiple clients.
-
Type a message in the text box and press Enter.
-
The message will be sent to all other connected clients.
- The
main.gofile contains the main logic of the WebSocket server. - The
github.com/gorilla/websocketpackage is used to enhance the functionality of thenet/httppackage. - The
HomeHandlerfunction handles the initial route and serves thepublic/index.htmlfile. - The
WsHandlerfunction is called when a client connects to the "/ws" route. - The
AddClientfunction adds the client to the list of connected clients. - The
BroadcastMessageToAllfunction sends a message to all connected clients. - The
BroadcastMessageToClientfunction sends a message to a specific client. - The
BroadcastMessageToOthersfunction sends a message to all clients except the specific client. - The
HandleClientMessagesfunction handles messages received from a client and broadcasts them to other clients. - The
CleanupClientsfunction checks client connections and removes disconnected clients from the list. - The
MonitorClientConnectionsfunction periodically checks client connections.
This project depends on the Gorilla WebSocket library. You can install it using the following command:
go get github.com/gorilla/websocketMake sure you have set up the Go environment correctly for the dependencies to be installed properly.
This is a simple example of a WebSocket server in Go. It allows multiple clients to connect and exchange real-time messages. Feel free to explore and modify the code to fit your specific needs.