如何构建一个发送和接收客户端的简单节点js服务器?

时间:2014-01-01 13:43:26

标签: javascript node.js

我有一个节点js服务器和一个html / javascript客户端。

我只是想让客户端将json-string发送到node.js服务器,服务器进程的那个字符串并将结果字符串返回给客户端。

我开始设置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);
            }
        }

和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);

但在服务器上我收到此错误:

    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)

非常感谢任何帮助。


更新

更新的服务器代码:

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.');
    });
});

这解决了我的问题,我现在收到了回复信息。

1 个答案:

答案 0 :(得分:1)

websocket不是普通的TCP套接字。这基本上是你问题的核心。

websocket协议看起来像一个修改过的HTTP协议,允许使用单个(TCP)套接字进行双向通信。阅读RFC以获取有关websocket协议实际工作原理的更多信息:http://tools.ietf.org/html/rfc6455#section-1.2

如果要将websockets与节点服务器一起使用,则有两个选项:

  1. 阅读RFC并编写一个函数来处理websocket协议,以便将该函数传递给socket.on。

  2. 使用其他人编写的websocket服务器模块。转到npm并搜索"websocket server"或Google "websocket server npm"。那里有很多模块。选择一个你最喜欢的。

  3. 还有第三种选择。使用socket.io。 Socket.io是一个库,如果可能的话,使用websocket在客户端和服务器之间进行通信(首选),但是能够降级到旧浏览器上的其他传输,例如Flash和ajax。