This is a simple websocket chat application.
The server and client were written in Go and VueJS.
See the Features
The websocket packaged used in this project is:
The ./public/script.js
file has a ENVIRONMENTS
const that can be used to
switch between the local server and the production server.
-
find and replace the
ENVIRONMENTS
const in./public/script.js
:search for
.PROD.
and replace it with.DEV.
:%s/\.PROD/.DEV/g
-
run the server:
go run ./main.go
To open a new WebSocket connection to the server, you have to pass the following query parameters:
nickname
: the nickname of the userroom
: the room name (optional, default:general
)
Example:
-
Connect to the
general
room with the nicknameJohn
:const ws = new WebSocket( `ws://localhost:3000/ws?nickname=John&room=general` );
-
Subscribe to see the messages from the ws:
ws.onmessage = (event) => { console.log(event.data); };
if you don't want to get spammed with the notifications, you can filter the messages:
ws.onmessage = (event) => { const data = JSON.parse(event.data); if (data.type === "message") { console.log(data); } };
-
Send a message to the server:
You can send two types of messages to the server:
message
andnotification
.message
: a message that will be displayed in the chatnotification
: the sender will be added to a list of who is typing (displayed below the chat)
3.1. Payload message format:
{ "type": "message", // string (required): accepted values = "message", "notification" "from": { "nickname": "John", // string (required): your nickname "color": "#000000", // string (optional): hexadecimal color (default: #000000) }, content: "Hello world!", // string (required for "message" type): the message content isTyping: true, // boolean (required for "notification" type): notifies other connected clients that you are typing }
3.2. Sending a Hello world! message:
ws.send( JSON.stringify({ type: "message", from: { nickname: "John", }, content: "Hello world!", }) );