기본 콘텐츠로 건너뛰기

[Node.js] Node.js 웹소켓 nodejs-websocket

[Node.js] Node.js 웹소켓 nodejs-websocket

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

출처: https://www.npmjs.com/package/nodejs-websocket

How to use it

Install with npm install nodejs-websocket or put all files in a folder called "nodejs-websocket", and:

var ws = require ( " nodejs-websocket " ) var server = ws . createServer ( function ( conn ) { console . log ( " New connection " ) conn . on ( " text " , function ( str ) { console . log ( " Received " + str ) conn . sendText ( str . toUpperCase ( ) + " !!! " ) } ) conn . on ( " close " , function ( code , reason ) { console . log ( " Connection closed " ) } ) } ) . listen ( 8001 )

Se other examples inside the folder samples

ws

The main object, returned by require("nodejs-websocket") .

Returns a new Server object.

The options is an optional object that will be handed to net.createServer() to create an ordinary socket. If it has a property called "secure" with value true , tls.createServer() will be used instead.

To support protocols, the options object may have either of these properties:

validProtocols : an array of protocol names the server accepts. The server will pick the most preferred protocol in the client's list.

: an array of protocol names the server accepts. The server will pick the most preferred protocol in the client's list. selectProtocol : a callback to resolve the protocol negotiation. This callback will be passed two parameters: the connection handling the handshake and the array of protocol names informed by the client, ordered by preference. It should return the resolved protocol, or empty if there is no agreement.

The callback is a function which is automatically added to the "connection" event.

Returns a new Connection object, representing a websocket client connection

URL is a string with the format "ws://localhost:8000/chat" (the port can be omitted)

options is an object that will be passed to net.connect() (or tls.connect() if the protocol is "wss:"). The properties "host" and "port" will be read from the URL . The optional property extraHeaders will be used to add more headers to the HTTP handshake request. If present, it must be an object, like {'X-My-Header': 'value'} . The optional property protocols will be used in the handshake (as "Sec-WebSocket-Protocol" header) to allow the server to choose one of those values. If present, it must be an array of strings.

callback will be added as "connect" listener

Sets the minimum size of a pack of binary data to send in a single frame (default: 512kiB)

Set the maximum size the internal Buffer can grow (default: 2MiB) If at any time it stays bigger than this, the connection will be closed with code 1009 This is a security measure, to avoid memory attacks

Server

The class that represents a websocket server, much like a HTTP server

Starts accepting connections on a given port and host .

If the host is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY).

A port value of zero will assign a random port.

callback will be added as an listener for the 'listening' event.

Stops the server from accepting new connections and keeps existing connections. This function is asynchronous, the server is finally closed when all connections are ended and the server emits a 'close' event. The optional callback will be called once the 'close' event occurs.

The underlying socket, returned by net.createServer or tls.createServer

An Array with all connected clients. It's useful for broadcasting a message:

function broadcast ( server , msg ) { server . connections . forEach ( function ( conn ) { conn . sendText ( msg ) } ) }

Emitted when the server has been bound after calling server.listen

Emitted when the server closes. Note that if connections exist, this event is not emitted until all connections are completely ended.

Emitted when an error occurs. The 'close' event will be called directly following this event.

Emitted when a new connection is made successfully (after the handshake have been completed). conn is an instance of Connection

Connection

The class that represents a connection, either a client-created (accepted by a nodejs ws server) or client connection. The websocket protocol has two types of data frames: text and binary. Text frames are implemented as simple send function and receive event. Binary frames are implemented as streams: when you receive binary data, you get a ReadableStream; to send binary data, you must ask for a WritableStream and write into it. The binary data will be divided into frames and be sent over the socket.

You cannot send text data while sending binary data. If you try to do so, the connection will emit an "error" event

Sends a given string to the other side. You can't send text data in the middle of a binary transmission.

callback will be added as a listener to write operation over the socket

Asks the connection to begin transmitting binary data. Returns a WritableStream. The binary transmission will end when the WritableStream finishes (like when you call .end on it)

Sends a single chunk of binary data (like calling connection.beginBinary().end(data))

callback will be added as a listener to write operation over the socket

Sends a given string or Buffer to the other side. This is simply an alias for sendText() if data is a string or sendBinary() if the data is a Buffer.

callback will be added as a listener to write operation over the socket

Sends a ping with optional payload

Starts the closing handshake (sends a close frame)

The underlying net or tls socket

If the connection was accepted by a nodejs server, a reference to it will be saved here. null otherwise

One of these constants, representing the current state of the connection. Only an open connection can be used to send/receive data.

connection.CONNECTING (waiting for handshake completion)

connection.OPEN

connection.CLOSING (waiting for the answer to a close frame)

connection.CLOSED

Stores the OutStream object returned by connection.beginBinary(). null if there is no current binary data beeing sent.

For a connection accepted by a server, it is a string representing the path to which the connection was made (example: "/chat"). null otherwise

Read only map of header names and values. Header names are lower-cased

Array of protocols requested by the client. If no protocols were requested, it will be an empty array.

Additional resources on websocket subprotocols:

The protocol agreed for this connection, if any. It will be an element of connection.protocols .

Emitted when the connection is closed by any side

Emitted in case of error (like trying to send text data while still sending binary data). In case of an invalid handshake response will also be emited.

Emitted when a text is received. str is a string

Emitted when the beginning of binary data is received. inStream is a ReadableStream:

var server = ws . createServer ( function ( conn ) { console . log ( " New connection " ) conn . on ( " binary " , function ( inStream ) { var data = new Buffer ( 0 ) inStream . on ( " readable " , function ( ) { var newData = inStream . read ( ) if ( newData ) data = Buffer . concat ( [ data , newData ] , data . length + newData . length ) } ) inStream . on ( " end " , function ( ) { console . log ( " Received " + data . length + " bytes of binary data " ) process_my_data ( data ) } ) } ) conn . on ( " close " , function ( code , reason ) { console . log ( " Connection closed " ) } ) } ) . listen ( 8001 )

Emitted when the connection is fully established (after the handshake)

Emitted when a pong is received, usually after a ping was sent. data is the pong payload, as a string

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

from http://202psj.tistory.com/1232 by ccl(A) rewrite - 2020-03-07 13:54:16

댓글

이 블로그의 인기 게시물

[Mac OS X] 데스크탑 응용프로그램 개발시작

[Mac OS X] 데스크탑 응용프로그램 개발시작 현재 회사에서 다음 프로젝트로 Mac OS X를 개발해야 하는 일정이 생겨 난생 처음 데스크탑 응용프로그램을 개발하기 공부를 시작했고 여러가지 플랫폼이 있다는것을 발견했다. 어떤 플랫폼을 사용해야할 지 먼저 고민해보자. 무엇으로 개발할것인가? Xcode & Swfit or Objective-C Mac OS X 는 objective-c를 기반으로 만들어졌다. apple에서 제공하는 Xcode와 objective-c 혹은 Swift로 응용 프로그램을 만들 수 있다. Electron Electron 프레임워크를 사용하면 javascript, HTML, CSS를 사용하여 크로스 플랫폼 데스크탑 응용 프로그램을 만들 수 있다. react-native-desktop Qt 프레임 워크를 기반으로하는 크로스 플랫폼이다. react-native 와 javascript로 응용 프로그램을 만들 수 있다. Qt는 컴퓨터 프로그래밍에서 GUI 프로그램 개발에 널리 쓰이는 크로스 플랫폼 프레임워크. 각 플랫폼의 장단점은 무엇인가? Xcode & Swfit or Objective-C - 장점 모든 OSX API에 직접 접근할 수 있다. Xcode를 통해 App Store에 쉽게 배포할 수 있다. - 단점 Windows 전용 응용 프로그램을 다시 개발해야한다. Swift언어를 모른다면 새로 공부해야 한다. Electron - 장점 웹스택을 가지고 빠르게 만들 수 있다. 다양한 플랫폼을 지원한다. - 단점 Native언어로 개발할때 보다 성능이 떨어질 이슈가있다. OS X API를 사용하는데 복잡하다. *API에 대한 JavaScript 래퍼가 없으면 자체 래퍼를 작성하지 않는 한 프로젝트에서 사용할 수 없습니다. React-native-desktop - 장점 현재 개발스택과 완전히 동일하므로 더 빠르게 개발 할 수 있다. 다양한 플랫폼을 지원한다. - 단점 N...

AWS CI/CD 파이프라인에 Slack 알람 적용(Lambda, CloudWatch Events 연동)

AWS CI/CD 파이프라인에 Slack 알람 적용(Lambda, CloudWatch Events 연동) 이번 글에서는 구축된 CI/CD 파이프라인과 Slack 알람을 연동하는 방법에 대해서 알아볼 것이다. CI/CD 파이프라인 시작/종료(성공/실패) 시 Amazon CloudWatch Events에서 해당 이벤트를 감지한 후 AWS Lambda로 트리거 신호를 보내면 AWS Lambda에서 Slack채널로 알람을 보내는 프로세스다. 글의 순서는 다음과 같다. Amazon CloudWatch Events, AWS Lambda란? 실습 전 준비사항 Slack Webhook 생성 AWS Lambda 함수 생성 AWS CloudWatch Events 생성 테스트 위와 같은 방식으로 구축을 하면 최종 프로세스는 다음 그림과 같다 (우리가 이 글에서 진행하는 내용은 빨간색으로 표시된 부분) 1. Amazon CloudWatch Events, AWS Lambda란? 1-1. Amazon CloudWatch Events란? Amazon CloudWatch Event(혹은 AWS CloudWatch Events)는 AWS 상태 변경 등을 감시할 수 있는 기능이다. 만약 사용자가 만든 규칙에 맞는 이벤트가 발생하게 되면 해당 이벤트가 사정에 정의된 규칙과 일치할 경우 하나 이상의 대상 작업을 호출한다. 이벤트 유형에 따라 알람을 보내거나, 이벤트 정보를 캡쳐하거나, 교정작업을 수행하거나, 이벤트를 시작하거나, 기타 작업을 수행할 수 있다. 이벤트가 발생할 경우 대상 작업은 AWS Lambda함수, AWS Kinesis 스트림, AWS SQS, Amazon SNS 등이 있다. 사용되는 사례로는 1) 이벤트가 발생하면 Lambda함수를 사용하여 Slack채널로 알림을 전달하거나, 2) AWS 상태 이벤트가 발생하면 Lambda 및 CloudWatch Events를 사용하여 Amazon SNS로 사용자 지정 텍스트 또는 SMS 알림을 보내는 등...

[2020-angstromCTF] web - A peculiar query write-up

[2020-angstromCTF] web - A peculiar query write-up English write-up UI seems like below. If you click the 'the source' link, you can get back-end source code. const express = require("express"); const rateLimit = require("express-rate-limit"); const app = express(); const { Pool, Client } = require("pg"); const port = process.env.PORT || 9090; const path = require("path"); const client = new Client({ user: process.env.DBUSER, host: process.env.DBHOST, database: process.env.DBNAME, password: process.env.DBPASS, port: process.env.DBPORT }); async function query(q) { const ret = await client.query(`SELECT name FROM Criminals WHERE name ILIKE '${q}%';`); return ret; } app.set("view engine", "ejs"); app.use(express.static("public")); app.get("/src", (req, res) => { res.sendFile(path.join(__dirname, "index.js")); }); app.get("/", async (req, res) => { if (req.query...