javascript websockets错误:在Socket.socketonData处解析错误

时间:2018-11-30 11:08:57

标签: javascript websocket

我有一个连接到本地服务器并从html页面启动的javascript,建立连接后出现此错误。从研究中,我相信它与标头有关,但是由于我对Websocket不太了解,因此不确定如何解决它。任何帮助将不胜感激。

代码:

serverStart()
function serverStart () {
  const WebSocket = require('ws')
  // The port number and hostname of the server.
  const client = new WebSocket('ws://127.0.0.1:15001', 'protocol1')
  // Send a connection request to the server.

  client.onopen = function () {
    document.getElementById('response').innerHTML = ('Connection established')
    // If there is no error, the server has accepted the request and created a new
    // socket dedicated to us.
    console.log('TCP connection established with the server.')
    //  send data to the server by writing to its socket.
    client.send('Hello, server.')
  }
  // receive data from the server by reading from its socket.
  client.onmessage = function (chunk) {
    console.log('Data received from the server:' + chunk.toString())
    document.getElementById('response').innerHTML = (`Data received from the server: ${chunk.toString()}.`)

    // Request an end to the connection after the data has been received.
  }
  client.onclose = function () {
    console.log('Requested an end to the TCP connection')
  }
  // error handler
  client.onError = function (evt) {
    console.log(evt)
  }
}

错误:

events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: Parse Error
    at Socket.socketOnData (_http_client.js:440:20)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
    at Socket.Readable.push (_stream_readable.js:208:10)
    at TCP.onread (net.js:601:20)

0 个答案:

没有答案