w279471172 2024-04-22 08:08 采纳率: 26.7%
浏览 12
已结题

WebSocket的问题

我用NODE建立一个WebSocket的服务器。想保存用户的链接信息。方便随时给客户端回消息 可是这个参数里的东西太多了
我只想要把用来连接的信息保存到数组里即可

//这个是我的服务器 绑定了HTTPS
const server = https.createServer(options);


const wss = new WebSocket.Server({ server});


wss.on('connection', (ws,req) => {

  console.log(req)
  ws.on('message', (message,) => {



  });


});

//下面这一堆里边那些是有用的 用来连接的IP   字数不让都写上来 我删除了一部分
server.listen(8080, () => {
  console.log('8080账号');
});





IncomingMessage {
  _readableState: ReadableState {
    state: 137394,
    highWaterMark: 16384,
    buffer: BufferList { head: null, tail: null, length: 0 },
    length: 0,
    pipes: [],
    flowing: null,
    errored: null,
    defaultEncoding: 'utf8',
    awaitDrainWriters: null,
    decoder: null,
    encoding: null,
    [Symbol(kPaused)]: null
  },
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  socket: <ref *1> TLSSocket {
    _tlsOptions: {
      secureContext: [SecureContext],
      isServer: true,
      server: [Server],
      requestCert: false,
      rejectUnauthorized: true,
      handshakeTimeout: 120000,
      ALPNProtocols: <Buffer 08 68 74 74 70 2f 31 2e 31>,
      ALPNCallback: undefined,
      SNICallback: [Function: SNICallback],
      enableTrace: undefined,
      pauseOnConnect: false,
      pskCallback: undefined,
      pskIdentityHint: undefined
    },
    _secureEstablished: true,
    _securePending: false,
    _newSessionPending: false,
    _controlReleased: true,
    secureConnecting: false,
    _SNICallback: null,
    servername: 'wenyuliou6789.com',
    alpnProtocol: 'http/1.1',
    authorized: false,
    authorizationError: null,
    encrypted: true,
    _events: [Object: null prototype] {
      close: [Array],
      end: [Array],
      newListener: [Function: keylogNewListener],
      secure: [Function: onServerSocketSecure],
      _tlsError: [Function: onSocketTLSError],
      data: [Function: socketOnData],
      error: [Function: socketOnError]
    },
    _eventsCount: 7,
    connecting: false,
    _hadError: false,
    _parent: Socket {
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: null,
      _closeAfterHandlingError: false,
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: [Server],
      _server: [Server],
      [Symbol(async_id_symbol)]: 132,
      [Symbol(kHandle)]: [TCP],
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kSetNoDelay)]: true,
      [Symbol(kSetKeepAlive)]: false,
      [Symbol(kSetKeepAliveInitialDelay)]: 0,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0
    },
    _host: null,
    _closeAfterHandlingError: false,
    _readableState: ReadableState {
      state: 4696,
      highWaterMark: 16384,
      buffer: BufferList { head: null, tail: null, length: 0 },
      length: 0,
      pipes: [],
      flowing: true,
      errored: null,
      defaultEncoding: 'utf8',
      awaitDrainWriters: null,
      decoder: null,
      encoding: null,
      [Symbol(kPaused)]: false
    },
    _maxListeners: undefined,
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: false,
      defaultEncoding: 'utf8',
      length: 129,
      writing: true,
      corked: 0,
      sync: false,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: [Function: nop],
      writelen: 129,
      afterWriteTickInfo: null,
      buffered: [],
      bufferedIndex: 0,
      allBuffers: true,
      allNoop: true,
      pendingcb: 1,
      constructed: true,
      prefinished: false,
      errorEmitted: false,
      emitClose: false,
      autoDestroy: true,
      errored: null,
      closed: false,
      closeEmitted: false,
      [Symbol(kOnFinished)]: []
    },
    allowHalfOpen: false,
    _sockname: null,
    _pendingData: null,
    _pendingEncoding: '',
    server: Server {
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      requestTimeout: 300000,
      headersTimeout: 60000,
      keepAliveTimeout: 5000,
      connectionsCheckingInterval: 30000,
      joinDuplicateHeaders: undefined,
      rejectNonStandardBodyWrites: false,
      _contexts: [],
      requestCert: false,
      rejectUnauthorized: true,
      ALPNCallback: undefined,
      ALPNProtocols: <Buffer 08 68 74 74 70 2f 31 2e 31>,
      pfx: undefined,
      key: <Buffer 2d 2d 2d 2d 2d 42 45 47 49 4e 20 52 53 41 20 50 52 49 56 41 54 45 20 4b 45 59 2d 2d 2d 2d 2d 0a 4d 49 49 45 6f 77 49 42 41 41 4b 43 41 51 45 41 6c 59 ... 1625 more bytes>,
      passphrase: undefined,
      cert: <Buffer 2d 2d 2d 2d 2d 42 45 47 49 4e 20 43 45 52 54 49 46 49 43 41 54 45 2d 2d 2d 2d 2d 0a 4d 49 49 47 46 6a 43 43 42 50 36 67 41 77 49 42 41 67 49 51 44 48 ... 3800 more bytes>,
      clientCertEngine: undefined,
      ca: undefined,
      minVersion: undefined,
      maxVersion: undefined,
      secureProtocol: undefined,
      crl: undefined,
      sigalgs: undefined,
      ciphers: undefined,
      ecdhCurve: undefined,
      dhparam: undefined,
      honorCipherOrder: true,
      secureOptions: undefined,
      sessionIdContext: '991cb383123c35b99181a0bece08f084',
      privateKeyIdentifier: undefined,
      privateKeyEngine: undefined,
      _sharedCreds: [SecureContext],
      _events: [Object: null prototype],
      _eventsCount: 6,
      _maxListeners: undefined,
      _connections: 1,
      _handle: [TCP],
      _usingWorkers: false,
      _workers: [],
      _unref: false,
      allowHalfOpen: false,
      pauseOnConnect: false,
      noDelay: true,
      keepAlive: false,
      keepAliveInitialDelay: 0,
      highWaterMark: 16384,
      httpAllowHalfOpen: false,
      timeout: 0,
      maxHeadersCount: null,
      _connectionKey: '6::::8080',
      [Symbol(IncomingMessage)]: [Function: IncomingMessage],
      [Symbol(ServerResponse)]: [Function: ServerResponse],
      [Symbol(handshake-timeout)]: 120000,
      [Symbol(snicallback)]: undefined,
      [Symbol(pskcallback)]: undefined,
      [Symbol(pskidentityhint)]: undefined,
      [Symbol(kCapture)]: false,
      [Symbol(async_id_symbol)]: 9,
      [Symbol(enableTrace)]: undefined,
      [Symbol(http.server.connections)]: ConnectionsList {},
      [Symbol(http.server.connectionsCheckingInterval)]: Timeout {
        _idleTimeout: 30000,
        _idlePrev: [TimersList],
        _idleNext: [Timeout],
        _idleStart: 287,
        _onTimeout: [Function: bound checkConnections],
        _timerArgs: undefined,
        _repeat: 30000,
        _destroyed: false,
        [Symbol(refed)]: false,
        [Symbol(kHasPrimitive)]: false,
        [Symbol(asyncId)]: 16,
        [Symbol(triggerId)]: 10
      }
    },
    _server: null,
    ssl: TLSWrap {
      _parent: [TCP],
      _parentWrap: [Socket],
      _secureContext: [SecureContext],
      reading: true,
      onkeylog: [Function: onkeylog],
      onhandshakestart: [Function: onhandshakestart],
      onhandshakedone: [Function: onhandshakedone],
      onclienthello: [Function: loadSession],
      oncertcb: [Function: loadSNI],
      onnewsession: [Function: onnewsession],
      lastHandshakeTime: 27883,
      handshakes: 0,
      onerror: [Function: onerror],
      _consumed: true,
      [Symbol(owner_symbol)]: [Circular *1]
    },
    _requestCert: false,
    _rejectUnauthorized: true,
    timeout: 0,
    parser: null,
    on: [Function (anonymous)],
    addListener: [Function (anonymous)],
    prependListener: [Function: prependListener],
    setEncoding: [Function: socketSetEncoding],
    _paused: false,
    [Symbol(alpncallback)]: null,
    [Symbol(res)]: TLSWrap {
      _parent: [TCP],
      _parentWrap: [Socket],
      _secureContext: [SecureContext],
      reading: true,
      onkeylog: [Function: onkeylog],
      onhandshakestart: [Function: onhandshakestart],
      onhandshakedone: [Function: onhandshakedone],
      onclienthello: [Function: loadSession],
      oncertcb: [Function: loadSNI],
      onnewsession: [Function: onnewsession],
      lastHandshakeTime: 27883,
      handshakes: 0,
      onerror: [Function: onerror],
      _consumed: true,
      [Symbol(owner_symbol)]: [Circular *1]
    },
    [Symbol(verified)]: false,
    [Symbol(pendingSession)]: null,
    [Symbol(async_id_symbol)]: 133,
    [Symbol(kHandle)]: TLSWrap {
      _parent: [TCP],
      _parentWrap: [Socket],
      _secureContext: [SecureContext],
      reading: true,
      onkeylog: [Function: onkeylog],
      onhandshakestart: [Function: onhandshakestart],
      onhandshakedone: [Function: onhandshakedone],
      onclienthello: [Function: loadSession],
      oncertcb: [Function: loadSNI],
      onnewsession: [Function: onnewsession],
      lastHandshakeTime: 27883,
      handshakes: 0,
      onerror: [Function: onerror],
      _consumed: true,
      [Symbol(owner_symbol)]: [Circular *1]
    },
    [Symbol(lastWriteQueueSize)]: 129,
    [Symbol(timeout)]: Timeout {
      _idleTimeout: -1,
      _idlePrev: null,
      _idleNext: null,
      _idleStart: 27882,
      _onTimeout: null,
      _timerArgs: undefined,
      _repeat: null,
      _destroyed: true,
      [Symbol(refed)]: false,
      [Symbol(kHasPrimitive)]: false,
      [Symbol(asyncId)]: 134,
      [Symbol(triggerId)]: 9
    },
    [Symbol(kBuffer)]: null,
    [Symbol(kBufferCb)]: null,
    [Symbol(kBufferGen)]: null,
    [Symbol(kCapture)]: false,
    [Symbol(kSetNoDelay)]: true,
    [Symbol(kSetKeepAlive)]: false,
    [Symbol(kSetKeepAliveInitialDelay)]: 0,
    [Symbol(kBytesRead)]: 0,
    [Symbol(kBytesWritten)]: 0,
    [Symbol(error-emitted)]: false,
    [Symbol(websocket)]: WebSocket {
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: undefined,
      _binaryType: 'nodebuffer',
      _closeCode: 1006,
      _closeFrameReceived: false,
      _closeFrameSent: false,
      _closeMessage: <Buffer >,
      _closeTimer: null,
      _extensions: {},
      _paused: false,
      _protocol: '',
      _readyState: 1,
      _receiver: [Receiver],
      _sender: [Sender],
      _socket: [Circular *1],
      _autoPong: true,
      _isServer: true,
      [Symbol(kCapture)]: false
    }
  },
  httpVersionMajor: 1,
  httpVersionMinor: 1,
  httpVersion: '1.1',
  complete: true,
  rawHeaders: [
    'Host',
    'wenyuliou6789.com:8080',
    'Connection',
    'Upgrade',
    'Pragma',
    'no-cache',
    'Cache-Control',
    'no-cache',
    'User-Agent',
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.289 Safari/537.36',     
    'Upgrade',
    'websocket',
    'Origin',
    'http://localhost:7456',
    'Sec-WebSocket-Version',
    '13',
    'Accept-Encoding',
    'gzip, deflate, br',
    'Accept-Language',
    'zh-CN,zh;q=0.9',
    'Sec-WebSocket-Key',
    'B7+3YdqZj8eSnuOkNfl1xw==',
    'Sec-WebSocket-Extensions',
    'permessage-deflate; client_max_window_bits'
  ],
  rawTrailers: [],
  joinDuplicateHeaders: null,
  aborted: false,
  upgrade: true,
  url: '/',
  method: 'GET',
  statusCode: null,
  statusMessage: null,
  client: <ref *1> TLSSocket {
    _tlsOptions: {
      secureContext: [SecureContext],
      isServer: true,
      server: [Server],
      requestCert: false,
      rejectUnauthorized: true,
      handshakeTimeout: 120000,
      ALPNProtocols: <Buffer 08 68 74 74 70 2f 31 2e 31>,
      ALPNCallback: undefined,
      SNICallback: [Function: SNICallback],
      enableTrace: undefined,
      pauseOnConnect: false,
      pskCallback: undefined,
      pskIdentityHint: undefined
    },
    _secureEstablished: true,
    _securePending: false,
    _newSessionPending: false,
    _controlReleased: true,
    secureConnecting: false,
    _SNICallback: null,
    servername: 'wenyuliou6789.com',
    alpnProtocol: 'http/1.1',
    authorized: false,
    authorizationError: null,
    encrypted: true,
    _events: [Object: null prototype] {
      close: [Array],
      end: [Array],
      newListener: [Function: keylogNewListener],
      secure: [Function: onServerSocketSecure],
      _tlsError: [Function: onSocketTLSError],
      data: [Function: socketOnData],
      error: [Function: socketOnError]
    },
    _eventsCount: 7,
    connecting: false,
    _hadError: false,
    _parent: Socket {
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: null,
      _closeAfterHandlingError: false,
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: [Server],
      _server: [Server],
      [Symbol(async_id_symbol)]: 132,
      [Symbol(kHandle)]: [TCP],
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kSetNoDelay)]: true,
      [Symbol(kSetKeepAlive)]: false,
      [Symbol(kSetKeepAliveInitialDelay)]: 0,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0
    },
    _host: null,
    _closeAfterHandlingError: false,
    _readableState: ReadableState {
      state: 4696,
      highWaterMark: 16384,
      buffer: BufferList { head: null, tail: null, length: 0 },
      length: 0,
      pipes: [],
      flowing: true,
      errored: null,
      defaultEncoding: 'utf8',
      awaitDrainWriters: null,
      decoder: null,
      encoding: null,
      [Symbol(kPaused)]: false
    },
    _maxListeners: undefined,
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: false,
      defaultEncoding: 'utf8',
      length: 129,
      writing: true,
      corked: 0,
      sync: false,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: [Function: nop],
      writelen: 129,
      afterWriteTickInfo: null,
      buffered: [],
      bufferedIndex: 0,
      allBuffers: true,
      allNoop: true,
      pendingcb: 1,
      constructed: true,
      prefinished: false,
      errorEmitted: false,
      emitClose: false,
      autoDestroy: true,
      errored: null,
      closed: false,
      closeEmitted: false,
      [Symbol(kOnFinished)]: []
    },
    allowHalfOpen: false,
    _sockname: null,
    _pendingData: null,
    _pendingEncoding: '',
    server: Server {
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      requestTimeout: 300000,
      headersTimeout: 60000,
      keepAliveTimeout: 5000,
      connectionsCheckingInterval: 30000,
      joinDuplicateHeaders: undefined,
      rejectNonStandardBodyWrites: false,
      _contexts: [],
      requestCert: false,
      rejectUnauthorized: true,
      ALPNCallback: undefined,
      ALPNProtocols: <Buffer 08 68 74 74 70 2f 31 2e 31>,
      pfx: undefined,

  • 写回答

23条回答 默认 最新

  • 阿里嘎多学长 2024-04-22 08:37
    关注
    获得0.15元问题酬金

    以下内容由CHATGPT及阿里嘎多学长共同生成、有用望采纳:


    问题概括

    这个问题的目的是要解决在Node.js环境下使用WebSocket时,如何从WebSocket连接请求中提取并保存有用的连接信息,特别是客户端的IP地址,以便能够随时向客户端发送消息。

    问题出现原因

    在WebSocket的连接请求中,包含了大量的信息,其中一些是必要的,而另一些可能对当前的应用场景并不重要。开发者希望从这些信息中提取出连接的IP地址,但可能不清楚如何从复杂的req对象中找到并使用所需的信息。

    问题解决方案

    要获取客户端的IP地址,可以通过req.socket对象来访问。以下是修改后的代码示例,展示了如何从WebSocket连接请求中提取客户端的IP地址,并将其保存到数组中。

    提供示例

    // 假设你已经有了HTTPS服务器
    const https = require('https');
    const fs = require('fs');
    const WebSocket = require('ws');
    const options = {
      key: fs.readFileSync('./path/to/key.pem'),
      cert: fs.readFileSync('./path/to/cert.pem'),
    };
    
    const server = https.createServer(options);
    const wss = new WebSocket.Server({ server });
    
    // 用来保存客户端IP的数组
    const clientIPs = [];
    
    wss.on('connection', (ws, req) => {
      // 获取客户端IP地址
      const ip = req.socket.remoteAddress;
    
      // 将IP地址保存到数组中
      clientIPs.push(ip);
    
      console.log(`客户端连接成功,IP地址为:${ip}`);
      
      ws.on('message', (message) => {
        console.log(`收到来自客户端的消息:${message}`);
      });
    
      ws.on('close', () => {
        // 这里可以处理连接关闭的逻辑
      });
    });
    
    server.listen(8080, () => {
      console.log('WebSocket服务器正在监听8080端口');
    });
    

    示例代码运行方式

    要运行此代码,你需要:

    1. 确保你的Node.js环境已经安装。
    2. 拥有一个有效的HTTPS密钥和证书(key.pemcert.pem),并将其路径替换到代码中的fs.readFileSync函数中。
    3. 在你的终端中运行此脚本。

    示例代码预期运行结果

    当你运行此代码,并有一个客户端连接到WebSocket服务器时,控制台将输出类似以下内容的信息:

    WebSocket服务器正在监听8080端口
    客户端连接成功,IP地址为:123.45.67.89
    

    这表明服务器已成功获取到客户端的IP地址,并且可以继续处理WebSocket消息。

    评论

报告相同问题?

问题事件

  • 系统已结题 4月30日
  • 创建了问题 4月22日

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址