WebSocket初识

WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。

在WebSocket API中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。

浏览器通过 JavaScript 向服务器发出建立 WebSocket 连接的请求,连接建立以后,客户端和服务器端就可以通过 TCP 连接直接交换数据。

当你获取 Web Socket 连接后,你可以通过 send() 方法来向服务器发送数据,并通过 onmessage 事件来接收服务器返回的数据。



Socket.readyState

只读属性 readyState 表示连接状态,可以是以下值:

  • 0 - 表示连接尚未建立。

  • 1 - 表示连接已建立,可以进行通信。

  • 2 - 表示连接正在进行关闭。

  • 3 - 表示连接已经关闭或者连接不能打开。

后端通过websocket-npm模块进行服务的支持

npm install ws ;

npm install websocket;

以下为代码实现(需优化)

html
< div id= "text" ></ div >
< div id= "mine" >
< h4 >我的 </ h4 >
</ div >
< div id= "share" >
< h4 >你的 </ h4 >
</ div >
< div id= "close" >
< h4 >关闭 </ h4 >

</div>

script

// Optional. You will see this name in eg. 'ps' or 'top' command
process. title = 'node-chat';

// Port where we'll run the websocket server
var webSocketsServerPort = 3001;

// websocket and http servers
var webSocketServer = require( 'websocket'). server;
var http = require( 'http');

var mysql = require ( "mysql")
var mysql = require( 'mysql');
var connections = mysql. createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'test'
});
connections. connect();

let data;
connections. query( 'SELECT * from user', function ( error, results, fields) {
if ( error) throw error;
data = results
});


var fs = require( 'fs');
// 文件名 // 文件内容 // 配置 // 回调
fs. writeFile( 'index.txt', "454844544454654",
{
//flag: 'a' //追加
},
function( err) {
if ( err) {
console. log( '出现错误!')
} else{
console. log( '已输出至index.txt中')
fs. stat( './index.txt', function( err, data){
console. log( data. size);
});
fs. readFile( './index.txt', 'utf8', function( err, data){
console. log( data);
});
}
})


/**
* Global variables
*/
// latest 100 messages
var history = [ ];
// list of currently connected clients (users)
var clients = [ ];

/**
* Helper function for escaping input strings
*/
function htmlEntities( str) {
return String( str). replace( /&/ g, '&'). replace( />/ g, '>'). replace( /"/ g, '"');
}

// Array with some colors
var colors = [ 'red', 'green', 'blue', 'magentas', 'purples', 'plums', 'orange' ];
// ... in random order
colors. sort( function( a, b) { return Math. random() > 0.5; } );

/**
* HTTP server
*/
var server = http. createServer( function( request, response) {
// Not important for us. We're writing WebSocket server, not HTTP server
});
server. listen( webSocketsServerPort, function() {
console. log(( new Date()) + " Server is listening on port " + webSocketsServerPort);
});

/**
* WebSocket server
*/
var wsServer = new webSocketServer({
// WebSocket server is tied to a HTTP server. WebSocket request is just
// an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6
httpServer: server
});

// This callback function is called every time someone
// tries to connect to the WebSocket server
wsServer. on( 'request', function( request) {
console. log(( new Date()) + ' Connection from origin ' + request. origin + '.');

// accept connection - you should check 'request.origin' to make sure that
// client is connecting from your website
// (http://en.wikipedia.org/wiki/Same_origin_policy)
var connection = request. accept( null, request. origin);
// we need to know client index to remove them on 'close' event
var index = clients. push( connection) - 1;
var userName = false;
var userColor = false;

console. log(( new Date()) + ' Connection accepted.');

// send back chat history
if ( history. length > 0) {
connection. sendUTF( JSON. stringify( { type: 'history', data: history} ));
}

// user sent some message
connection. on( 'message', function( message) {
//接收到的数据
console. log( message)
if ( message. type === 'utf8') {
if ( message. utf8Data === '') {
connection. sendUTF( JSON. stringify( data))
setInterval( function(){
connections. query( 'SELECT * from user', function ( error, results, fields) {
if ( error) throw error;
connection. sendUTF( JSON. stringify( results))
});
}, 5000)
} else{
connection. sendUTF( "love you to ")
}
} else{
connection. sendUTF( data)
} // accept only text
// if (userName === false) { // first message sent by user is their name
// // remember user name
// userName = htmlEntities(message.utf8Data);
// // get random color and send it back to the user
// userColor = colors.shift();
// connection.sendUTF(JSON.stringify({ type:'color', data: userColor }));
// console.log((new Date()) + ' User is known as: ' + userName
// + ' with ' + userColor + ' color.');

// } else { // log and broadcast the message
// console.log((new Date()) + ' Received Message from '
// + userName + ': ' + message.utf8Data);

// // we want to keep history of all sent messages
// var obj = {
// time: (new Date()).getTime(),
// text: htmlEntities(message.utf8Data),
// author: userName,
// color: userColor
// };
// history.push(obj);
// history = history.slice(-100);

// // broadcast message to all connected clients
// var json = JSON.stringify({ type:'message', data: obj });
// for (var i=0; i < clients.length; i++) {
// clients[i].sendUTF(json);
// }
// }
// }
});

// user disconnected
connection. on( 'close', function( connection) {
console. log( "关闭了")
// if (userName !== false && userColor !== false) {
// console.log((new Date()) + " Peer "
// + connection.remoteAddress + " disconnected.");
// // remove user from the list of connected clients
// clients.splice(index, 1);
// // push back user's color to be reused by another user
// colors.push(userColor);
// }
});

});


猜你喜欢

转载自blog.csdn.net/qinlulucsdn/article/details/80664049