写了一个简单的demo,直接上代码吧。用的时候注意一下版本号,可能 socket.io 的 API 有修改~
效果图
index.html
<!DOCTYPE <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>websocket测试</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- <link rel="stylesheet" type="text/css" media="screen" href="main.css" /> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.dev.js"></script>
<style>
* {margin:0; padding:0;}
html {background-color:#fff; }
#footer {border:0 solid #c3c3c3; position: fixed; height: 40px; width:98%; bottom:10px; left:1%; display:flex; flex:1; padgint:10px 0;}
.btn {background-color:#1AAD19; color:#fff; box-sizing:border-box; pading:0 1.32em; line-height:2.3; border-radius:5px; width:100px; display:inline-block; font-size:13px; text-align:center; text-decoration:none;height:40px;line-height:40px;font-size:16px;1}
.ipt {border:0; outline:0; background-color:transparent; font-size:17px; height:1.47em; line-height:1.47; width:100%; height:100%;} .ipt_container {display:flex; flex:1; border-top:1px solid #e5e5e5; border-bottom:1px solid #e5e5e5;} .btn_container {ymargin:0 10px;} #main {width:98%; height: 90%; margin:10px auto; display:block;}
#main textarea {border:1px solid #ddd; width:100%; height:100%; padding:5px; line-height:22px; font-size:14px;} /* .ipt_container:before {content:" "; position:absolute; top:0; left:0; height:1px; border-top:1px solid #e5e5e5; color:#e5e5e5;transform:scaleY(0.5); z-index:2; transform-origin:0 0;}
.ipt_container:after {content:" "; position:absolute; bottom:0; right:0; height:1px; border-bottom:1px solid #e5e5e5; color:#e5e5e5;transform:scaleY(0.5); z-index:2; transform-origin:0 100%;} */
</style>
</head>
<body> <div id="wrapper">
<div id="main">
<textarea readonly="readonly" id="txtConsole"></textarea>
</div>
<div id="footer">
<div class="ipt_container">
<input type='text' class="ipt" placeholder="请输入内容..." id="chatpIpt"/>
</div>
<div class="btn_container">
<a href="javascript:;" class="btn" onclick="sendMsgHandler();return false;">发送</a>
</div>
</div>
</div> <script type="text/javascript">
// common function
function getEl(id) {
return typeof(id) === 'string' ? document.getElementById(id) : null;
} // native code
// var websocket = new WebSocket('ws://127.0.0.1:8080/'); // websocket.addEventListener('error', function (evt) {
// console.log('websocket error.')
// }); // websocket.addEventListener('open', function (evt) {
// console.log('websocket open.')
// }); // websocket.addEventListener('message', function (evt) {
// console.log(evt.data);
// }); // websocket.addEventListener('close', function (evt) {
// console.log('websocket close.')
// }) // Create SocketIO instance, connect
var socket = io.connect('ws://localhost:8080'); // Add a connect listener
socket.on('connect', function() {
showMessage('Client has connected to the server!');
}); // Add a connect listener
socket.on('news', function(data) {
var str = 'Received data from server. data : ' + JSON.stringify(data);
showMessage(str);
}); // Add a disconnect listener
socket.on('disconnect', function() {
showMessage('The client has disconnected');
}); // Sends a message to the server via sockets
function sendMessageToServer(msgData) {
socket.emit('test_event', msgData);
} var delayScrollTimer = null;
function showMessage(str) {
var txt = getEl('txtConsole') txt.value = txt.value + '\n' + str; if (delayScrollTimer) {
clearTimeout(delayScrollTimer);
delayTimer = null;
} delayScrollTimer = setTimeout(function() {
txt.scrollTop = txt.scrollHeight;
}, 10);
} // test
function sendMsgHandler() {
var elem = getEl('chatpIpt'); var iptValue = elem.value; sendMessageToServer({data : iptValue}); elem.value = "";
elem.focus();
}
</script> </body>
</html>
socket_server.js
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs'); app.listen(8080); function handler(req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hello Socket Lover!</h1>');
} io.on('connection', function (socket) {
socket.emit('news', { data : 'server world' }); socket.on('test_event', function (data) {
console.log('receive data from client. data : ' + JSON.stringify(data)); var str = data.data + "(from server by " + new Date().getTime() + ")";
socket.emit('news', { data : str});
}); socket.on('disconnect', function () {
console.log('websocket close. -- server log');
}); // var num = 1;
// setInterval(function xx(params) {
// socket.emit('news', { num: num++});
// }, 1 * 1000);
});