我想创建一个react js应用程序作为web-socket客户端,其中反应js将请求我已在节点js中创建并在端口号1234上工作的服务器。
我是初学者对js作出反应。在我的应用程序中,js客户端没有请求节点js服务器。我在以下代码中遗漏了什么?
Node_js服务器 -
var server = require('websocket').server, http = require('http');
require('events').EventEmitter.prototype._maxListeners = 100;
nconf = require('nconf');
var socket = null;
var connection = null;
var filePath = ''
var timeInteval = 0
var LineByLineReader;
var sleep = require('sleep');
function init(){
nconf.argv().env().file({file: 'config.json'});
filePath = nconf.get('file-path');
timeInteval = nconf.get('time-inteval');
}
var main = function () {
init();
socket = new server({
httpServer: http.createServer().listen(1234)
});
console.log('Waiting for Client... On Port No : 1234');
socket.on('request', function (request) {
connection = request.accept(null, request.origin);
var connections = []
connections.push(connection);
console.log(connection.remoteAddress + '=====>>> Connection accepted.');
var lineReader = require('line-reader');
lineReader.eachLine(filePath, function(line, last) {
for (var i = 0; i < connections.length; i++) {
connections[i].sendUTF(line);
}
sleep.sleep(timeInteval)
});
connection.on('message', function (message) {
});
connection.on('close', function (connection) {
console.log('=====>>> Connection closed');
var index = connections.indexOf(connection);
connections.splice(index, 1);
});
connection.on('error', function (connection) {
console.log(connection.remoteAddress + ' : error');
});
});
}
if (require.main === module) {
main();
}
此节点js服务器适用于任意数量的客户端。
App.jsx -
var React = require('react')
var ws = require('ws');
var ReactDOM = require('react-dom');
const Echo = React.createClass({
getInitialState(){
return { messages : [] }
},
componentDidMount: function() {
var wsc = new ws('ws://localhost:1234');
wsc.onmessage = function(message) {
this.setState({ messages: message.data });
}.bind(this);
},
render: function() {
return ( this.state.messages );
}
});
const component = ReactDOM.render(
<Echo />,
document.getElementById('container')
);
的index.html -
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id="container">
</div>
<script src = "index.js"></script>
</body>
</html>
webpack.config.js -
var config = {
entry: './App.jsx',
output: {
path:'./',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8090
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;