What is WebSocket
The following HTML5 WebSocket is a technology designed purpose is to replace polling and Comet technology, the client browser with real-time communications capabilities like under C / S architecture of desktop systems. Sent to the browser via JavaScript WebSocket server request to establish a connection after the connection is established, the client and the server can directly exchange data via TCP connection. Because WebSocket connection is essentially a TCP connection, so in terms of size stability and data transfer amount data transmission, and the polling and Comet technology, compared with a significant performance advantage.
Simply put, this is a socket protocol can be accessed through the web.
Specific reference to the following:
https://www.websocket.org/
https://developer.mozilla.org/en-US/docs/WebSockets
What is websocketd
websocketd is a simple websocket service Server, run in command-line mode, and can interact through websocketd already have programs.
You can write a program to read and write, and STDIN and STDOUT websocketd interaction. Because it is a standard interface to read and write, so you can use any language to deal with.
Project address the program are as follows:
https://github.com/joewalnes/websocketd
websocketd 10 Miao Tutorial
1. Download and install websocketd
In fact, the websocketd downloaded to any local directory, anyway, you know the way you can run, then you can easily put
/usr/local/bin
Under contents. Download the latest project directly in the address on it.
2. Write a program to display data to STDOUT
You can use any language.
Examples of using the simplest sh.
count.sh:
#!/bin/bash
# Count from 1 to 10, pausing for a second between each iteration.
for COUNT in $(seq 1 10); do echo $COUNT sleep 1 done
Remember to let him into the executable file:
$ chmod +x ./count.sh
3. Start websocketd server
$ websocketd --port=8080 ./count.sh
4. javascript to write a client to interact
count.html:
<!DOCTYPE html>
<pre id="log"></pre> <script> // helper function: log message to screen function log(msg) { document.getElementById('log').textContent += msg + '\n'; } // setup websocket with callbacks var ws = new WebSocket('ws://localhost:8080/'); ws.onopen = function() { log('CONNECT'); }; ws.onclose = function() { log('DISCONNECT'); }; ws.onmessage = function(event) { log('MESSAGE: ' + event.data); }; </script>
Very short answer, to establish a connection, and then receive the message, of course, you can also send messages.
5.websocket common API
onopen
onerror
onclose
onmessage
send
Remarks: websocketd --port=8080 [执行指定程序] 例如: php count.php