websocket初探学习分享

本文主要是使用的心得,参考的网址是websocket,本例中使用的是Websocket-Node 服务器模式,本地全局安装node即可
服务端文件,本文命名为socketserver.js ,代码如下:

var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(8080, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  return true;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }
    
    var connection = request.accept('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

然后编写客户端文件index.html




    
    
    
    webSocket学习
    


     

编写完成以后,保存两个文件,在文件所在目录下打开控制台输入

node socketserver.js

在网页上就能进行尝试了,如图


image.png

点击发送:


image.png

本次尝试的直是单页面的,下次尝试多页面的通信,做成一个仿聊天室的再见。如有不对,欢迎指正

你可能感兴趣的:(websocket初探学习分享)