我写了一个服务器程序 server.js 如下
var SerialPort = require("serialport").SerialPort
var io = require('socket.io').listen(80);
var serialPort = new SerialPort("COM4", {
baudrate: 9600
});
serialPort.on("open", function () {
console.log('open');
serialPort.on('data', function(data) {
console.log('data received: ' + data);
});
serialPort.write("ls\n", function(err, results) {
console.log('err ' + err);
console.log('results ' + results);
//io.sockets.emit('message', 'data');
});
});
io.sockets.on('connection', function (socket) {
// If socket.io receives message from the client browser then
// this call back will be executed.
socket.on('message', function (msg) {
console.log(msg);
});
// If a web browser disconnects from Socket.IO then this callback is called.
socket.on('disconnect', function () {
console.log('disconnected');
});
});
var cleanData = ''; // this stores the clean data
var readData = ''; // this stores the buffer
serialPort.on('data', function (data) { // call back when data is received
readData += data.toString(); // append data to buffer
// if the letters 'A' and 'B' are found on the buffer then isolate what's in the middle
// as clean data. Then clear the buffer.
if (readData.indexOf('B') >= 0 && readData.indexOf('A') >= 0) {
cleanData = readData.substring(readData.indexOf('A') + 1, readData.indexOf('B'));
readData = '';
io.sockets.emit('message', cleanData);
}
});
客户端程序是(index.html)
<html>
</head>
<link type="text/css" href="/css/smoothness/jquery-ui-1.8.20.custom.css" rel="Stylesheet" />
<script type="text/javascript" src="//localhost:8000/socket.io/socket.io.js"></script>
<script type="text/javascript" src="/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="/js/jquery-ui-1.8.20.custom.min.js"></script>
<script>
var socket = io.connect('http://localhost:8000');
socket.on('connect', function () {
socket.on('message', function (msg) {
// Convert value to integer
var val = ((parseInt(msg) / 1023)*100);
// Put sensor value to the 'sensor_value' span
$('#sensor_value').html(val);
});
});
});
</script>
</head>
<body>
<div role="main">
Potentiometer Value: <span id="sensor_value"></span><br/>
</div>
</body>
</html>
我正在使用 WAMP 作为 Web 服务器 服务器控制台正在给我所需的输出。但是网页 index.html 中没有任何内容