服务端
var server = require(‘ws‘).Server; var serv = new server({port:8080}); serv.on(‘connection‘,function(socket){ socket.send(‘hello client‘) socket.on(‘message‘, function (data) { console.log(‘receive:‘,data); socket.send(‘receive:‘+data) }) })
页面客户端
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script> var socket = new WebSocket(‘ws://localhost:8080‘); socket.onopen = function(){ console.log(‘链接成功‘); socket.send(‘hello server‘); } socket.onmessage = function(e){ console.log(e.data) } </script> </body> </html>
时间: 2024-10-12 07:29:17