Browse Source

Renamed Files Added Connector

master
Paul Turowski 4 years ago
parent
commit
5e0c7ace19
4 changed files with 67 additions and 7 deletions
  1. 25
    0
      Connect.js
  2. 6
    6
      HtmlPage.html
  3. 0
    1
      JavaScript.js
  4. 36
    0
      Server.js

+ 25
- 0
Connect.js View File

@@ -0,0 +1,25 @@
let socket = new WebSocket("wss://javascript.info/article/websocket/demo/hello");

socket.onopen = function (e) {
alert("[open] Connection established");
alert("Sending to server");
socket.send("My name is John");
};

socket.onmessage = function (event) {
alert(`[message] Data received from server: ${event.data}`);
};

socket.onclose = function (event) {
if (event.wasClean) {
alert(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
} else {
// e.g. server process killed or network down
// event.code is usually 1006 in this case
alert('[close] Connection died');
}
};

socket.onerror = function (error) {
alert(`[error] ${error.message}`);
};

+ 6
- 6
HtmlPage.html View File

@@ -40,13 +40,13 @@
<input type="submit" value="Go!">
</form>
<th>Bezeichnung</th>
<th>Kaufort</th>
<th>Anz</th>
<th>E-Preis</th>
<th>G-Preis</th>
<table class="table">
<th>Bezeichnung</th>
<th>Kaufort</th>
<th>Anz</th>
<th>E-Preis</th>
<th>G-Preis</th>
<script type="text/javascript">
//var mydata = JSON.parse(stadtbezirk);
var sumpreis = 0;

+ 0
- 1
JavaScript.js View File

@@ -1 +0,0 @@


+ 36
- 0
Server.js View File

@@ -0,0 +1,36 @@

const http = require('http');
const ws = require('ws');

const wss = new ws.Server({ noServer: true });

function accept(req, res) {
// all incoming requests must be websockets
if (!req.headers.upgrade || req.headers.upgrade.toLowerCase() != 'websocket') {
res.end();
return;
}

// can be Connection: keep-alive, Upgrade
if (!req.headers.connection.match(/\bupgrade\b/i)) {
res.end();
return;
}

wss.handleUpgrade(req, req.socket, Buffer.alloc(0), onConnect);
}

function onConnect(ws) {
ws.on('message', function (message) {
let name = message.match(/([\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]+)$/gu) || "Guest";
ws.send(`Hello from server, ${name}!`);

setTimeout(() => ws.close(1000, "Bye!"), 50000);
});
}

if (!module.parent) {
http.createServer(accept).listen(8080);
} else {
exports.accept = accept;
}

Loading…
Cancel
Save