Last active
January 22, 2018 06:05
-
-
Save fhemberger/4183575 to your computer and use it in GitHub Desktop.
Beispielcode für "Client-Server-Kommunikation mit Socket.io" (Webkrauts-Adventskalender 2012)
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Socket.io Test</title> | |
<!-- Dieses Script wird von Socket.io automatisch zu Verfügung gestellt --> | |
<script src="/socket.io/socket.io.js"></script> | |
<script> | |
// Mit dem Socket.io-Server verbinden | |
var socket = io.connect('http://localhost:8080'); | |
// Warten auf Nachrichten | |
socket.on('welcome', function (data) { | |
console.log('[socket.io] "welcome"-Event vom Server empfangen:\n' + data); | |
// Eigenen Event vom Client an den Server schicken | |
socket.emit('user agent', navigator.userAgent); | |
}); | |
</script> | |
</head> | |
<body></body> | |
</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
// Kleiner HTTP-Server auf Port 8080 | |
var app = require('http').createServer(serveStaticIndex).listen(8080); | |
// Laden von Socket.io (Gibt für die Demo nur Fehler/Warnungen auf der Konsole aus) | |
// Update (2018-01-22): In aktuellen socket.io-Versionen muss das ".set('log level', 1);" weggelassen werden. | |
var io = require('socket.io').listen(app).set('log level', 1); | |
// Zugriff auf das Dateisystem (zum Ausliefern der index.html) | |
var fs = require('fs'); | |
// Liefert die Startseite aus | |
function serveStaticIndex(req, res) { | |
var fileStream = fs.createReadStream(__dirname + '/index.html'); | |
res.writeHead(200); | |
fileStream.pipe(res); | |
} | |
// Socket.io-Events | |
io.sockets.on('connection', function (socket) { | |
console.log('[socket.io] Ein neuer Client (Browser) hat sich verbunden.\n'); | |
console.log('[socket.io] SENDE "welcome"-Event an den Client.\n'); | |
socket.emit('welcome', "Hello world"); | |
socket.on('user agent', function (data) { | |
console.log('[socket.io] EMPFANGE "user agent"-Event vom Client:'); | |
console.log(data, '\n'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment