[英]How do I build a simple node js server that sends and receives to a client?
I have a node js server, and a html/javascript client. 我有一个节点js服务器和一个html / javascript客户端。
I simply want to allow the client to send a json-string to the node.js server, the server process's that string and returns a result string back to the client. 我只想允许客户端将json-string发送到node.js服务器,服务器进程就是该字符串,然后将结果字符串返回给客户端。
I started by setting up the html-client to call like so : 我首先通过设置html-client进行调用,如下所示:
var msg =
{
type: "message",
text: "Hello"
};
function CallWebSocket()
{
var socket = new WebSocket("ws://127.0.0.1:8080","test");
socket.onopen = function (event)
{
alert(JSON.stringify(msg));
socket.send(JSON.stringify(msg));
};
socket.onmessage = function(event)
{
alert(event.data);
}
}
and node.js : 和node.js:
var net = require('net');
var server = net.createServer(function(socket)
{
// do what you need
socket.setEncoding("utf8");
socket.on('data', function(data)
{
var jsonData = JSON.parse(data);
socket.write(jsonData.text);
socket.end();
process.exit(0);
});
});
server.listen(8080);
but on the server I get this error : 但是在服务器上我得到这个错误:
undefined:1
``GET / HTTP/1.1
^
SyntaxError: Unexpected token G
at Object.parse (native)
at Socket.<anonymous> (/home/jay/projects/nodejs/test/json-server.js:8:23)
at Socket.EventEmitter.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:746:14)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
at emitReadable (_stream_readable.js:404:5)
at readableAddChunk (_stream_readable.js:165:9)
at Socket.Readable.push (_stream_readable.js:127:10)
at TCP.onread (net.js:526:21)
Any help is much appreciated. 任何帮助深表感谢。
UPDATE 更新
The updated server code : 更新的服务器代码:
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,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed 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.');
});
});
This solved my problem and I am now getting the message back. 这解决了我的问题,现在我又收到了消息。
A websocket is not a plain TCP socket. Websocket不是普通的TCP套接字。 That is basically the core of your problem.
这基本上是您问题的核心。
The websocket protocol looks like a modified HTTP protocol that allows two way communication using a single (TCP) socket. Websocket协议看起来像是经过修改的HTTP协议,该协议允许使用单个(TCP)套接字进行双向通信。 Read the RFC for more info on how the websocket protocol actually works: http://tools.ietf.org/html/rfc6455#section-1.2
阅读RFC,了解有关Websocket协议实际工作方式的更多信息: http : //tools.ietf.org/html/rfc6455#section-1.2
You have two options if you want to use websockets with node servers: 如果要对节点服务器使用websocket,则有两个选择:
Read the RFC and write a function to handle the websocket protocol so you can pass that function to socket.on. 阅读RFC并编写一个函数来处理websocket协议,以便可以将该函数传递给socket.on。
Use a websocket server module that someone else have written. 使用别人编写的websocket服务器模块。 Go to npm and search for "websocket server" or google "websocket server npm" .
转到npm并搜索“ websocket服务器”或google “ websocket服务器npm” 。 There are lots of modules out there.
有很多模块。 Pick one you like best.
选择一个最喜欢的。
There is a third alternative. 还有第三种选择。 Use socket.io .
使用socket.io 。 Socket.io is a library that communicates between client and server using websocket if possible (preferred) but is able to degrade to other transports such as Flash and ajax on older browsers.
Socket.io是一个库,可以(如果可能)使用websocket在客户端和服务器之间进行通信(首选),但是可以降级到其他传输,例如旧版浏览器上的Flash和ajax。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.