簡體   English   中英

我如何構建一個簡單的節點js服務器來發送和接收到客戶端?

[英]How do I build a simple node js server that sends and receives to a client?

我有一個節點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.');
    });
});

這解決了我的問題,現在我又收到了消息。

Websocket不是普通的TCP套接字。 這基本上是您問題的核心。

Websocket協議看起來像是經過修改的HTTP協議,該協議允許使用單個(TCP)套接字進行雙向通信。 閱讀RFC,了解有關Websocket協議實際工作方式的更多信息: http : //tools.ietf.org/html/rfc6455#section-1.2

如果要對節點服務器使用websocket,則有兩個選擇:

  1. 閱讀RFC並編寫一個函數來處理websocket協議,以便可以將該函數傳遞給socket.on。

  2. 使用別人編寫的websocket服務器模塊。 轉到npm並搜索“ websocket服務器”或google “ websocket服務器npm” 有很多模塊。 選擇一個最喜歡的。

還有第三種選擇。 使用socket.io Socket.io是一個庫,可以(如果可能)使用websocket在客戶端和服務器之間進行通信(首選),但是可以降級到其他傳輸,例如舊版瀏覽器上的Flash和ajax。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM