-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add solutions for introductory NodeJS
- Loading branch information
Showing
3 changed files
with
52 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 |
---|---|---|
@@ -1 +1,29 @@ | ||
// Your code goes here | ||
// Your code goes here | ||
|
||
const {HttpServer, WebSocket, WebSocketMessage, Log} = require('@aliceo2/web-ui'); | ||
|
||
const logger = new Log('workshop-2023'); | ||
|
||
const http = new HttpServer({ | ||
port: 8080 | ||
}, { | ||
expiration: '60s' | ||
}); | ||
|
||
http.addStaticPath('public'); | ||
|
||
http.get('/hello-world', (_, res) => { | ||
res.status(200).json({message: 'Hello World!'}); | ||
}, {public: true}); | ||
|
||
http.get('/hello-private', (_, res) => { | ||
res.status(200).json({message: 'Hi, there'}) | ||
}); | ||
|
||
const ws = new WebSocket(http); | ||
|
||
ws.bind('hello', (message) => { | ||
console.log('Server received:', message); | ||
logger.info('test') | ||
return new WebSocketMessage().setCommand('hello-back').setPayload("hello back"); | ||
}); |
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,6 @@ | ||
<html> | ||
<body> | ||
<h1> Hello World!</h1> | ||
</body> | ||
<script src="./index.js" type="module"></script> | ||
</html> |
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,17 @@ | ||
// Little hack to get token from URL | ||
const url = new URL(window.location); | ||
const token = url.searchParams.get('token'); | ||
|
||
// Connect to WebSocket | ||
let webSocketConnector = new WebSocket('ws://localhost:8080?token=' + token); | ||
|
||
// Send message when connection open | ||
webSocketConnector.onopen = function () { | ||
console.log('Connected'); | ||
webSocketConnector.send('{"command":"hello", "payload":"hello, world!", "token": "' + token + '"}'); | ||
}; | ||
// Send message when connection open | ||
webSocketConnector.onmessage = function (message) { | ||
console.log(message) | ||
}; | ||
|