My first websocket practice!
Backend: wsserver.js
- Create the websocket server and wait for connections
- Forward the message to other clients when a message is received
Frontend: index.html & wsclient.js
- Establish a websocket with the server
- Check if the connection is successful
- Send messages to the server
- Basic node.js
- ws library
- Message forwarding techniques
- Basic jQuery grammar
- How to create websockets
- How to manipulate elements with jQuery statements
- In html,
id
is case-sensitive!!! - To use jQuery, add
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
(You may change the link to other CDNs) before other code. - What does
$(function() {*});
do? The function inside is executed when the page is ready. (https://stackoverflow.com/questions/7642442/what-does-function-do) - I learned this from https://medium.com/@martin.sikora/node-js-websocket-simple-chat-tutorial-2def3a841b61
- If the user is using mozilla, we should use its built-in websocket. To use the apporiate websocket, we can do it like this:
window.WebSocket = window.WebSocket || window.MozWebSocket;
- To create the websocket:
var conn = new WebSocket("ws://" + location.hostname + ":8080");
- You can use
$(this)
within an event handler for an element. - The websocket server should not forward the message to the client who sent the message. To do this:
wss.clients.forEach(function(client) {
if (client !== ws && client.readyState === websocket.OPEN) {
client.send(data);
}
});