기본 콘텐츠로 건너뛰기

[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

댓글

이 블로그의 인기 게시물

카카오 오픈빌더와 외부 API 연동(feat.Nodejs)

카카오 오픈빌더와 외부 API 연동(feat.Nodejs) 이전에 플러스 친구와 외부 API 연동에 관한 글을 작성한 적 있습니다. 하지만 지난 2년동안 플러스 친구에 많은 변화가 생겼는데요. 카카오 플러스 친구의 명칭이 카카오 채널로 바뀌고, 챗봇 세팅 방식이 기존 [카카오 플러스 친구 - 외부 API 연동] 구조에서 오픈빌더가 추가되어 [카카오 채널(구 플러스 친구) - 카카오 i 오픈빌더 - 외부 API 연동] 구조로 바뀌었습니다. 이번 글에서는 오픈빌더의 챗봇 시나리오 관리 기능을 간단히 소개하고 외부 API를 연동하는 예제를 다뤄보겠습니다. (연동파트는 5번 항목부터 보시면 됩니다.) 1. 블록 블록은 오픈빌더에서 질의/응답을 관리하는 최소 단위로, 사용자의 발화와 챗봇의 대답을 입력할 수 있습니다. 예를들어 인사라는 블록을 만들고 인사에 해당하는 사용자 발화 패턴들을 입력해두면, 실제 채널 톡방에서 그에 해당하는 발화가 들어왔을때 입력해둔 응답이 나오는 형식입니다. 예전에는 패턴과 발화 키워드가 1:1 매칭, 즉 입력해둔 패턴과 사용자 발화의 string이 정확히 일치할때만 블록이 실행됐었는데, 발화 패턴을 20개 이상 등록하면 머신러닝 기능을 이용할 수 있도록 기능이 생겼습니다. 아마 유사도 분석 개념이 기본으로 들어가있을 것이기 때문에 블록의 주제와 벗어나는 너무 뜬금없는 발화패턴들을 많이 넣지 않도록 하는걸 권장하겠습니다. 2. 시나리오 시나리오는 '블록'들을 묶어서 관리할 수 있는 단위로, 일종의 폴더 구조라고 생각하면 쉽습니다. 오픈빌더에서 좌측 상단에 파란 버튼을 클릭하여 시나리오를 생성할 수 있습니다. 하나의 시나리오에서 모든 블록을 관리하면 챗봇 도메인이 커질수록 관리가 어려워지니 아래 같은식으로 시나리오를 사용하여 블록을 구조화하면 운영 측면에서 수월해집니다. 3. 컨텍스트 컨텍스트는 맥락이라는 뜻 입니다. 오픈빌더에 존재하는 컨텍스트는 자연어 분석을 통해서 맥...

AWS instance로 Nodejs 구현하기

AWS instance로 Nodejs 구현하기 서버와 데이터베이스 관리 차원에서 효율적으로 관리하기 위해선 로컬보다는 서버를 호스팅해서 하는 것이 좋다. 우리는 Nodejs를 구동하기 위해 AWS에서 인스턴스를 할당받을 계획이다. 인스턴스의 pem키를 발급받아 nodejs와 npm까지는 설치를 완료한 상태이다. $ sudo npm install -g express 다음의 명령어를 입력하면 글로벌 옵션으로 어느 path에서든 express를 사용할 수 있게 설치한다. 다음과 같이 실행이 된다면 성공이다. 이후 Express generator를 설치한다. $ sudo npm install -g express-generator@4 버전은 4.x이며 이 역시 글로벌 옵션으로 설치해 준다. 이제 Node monitoring을 위해 nodemon을 설치해 준다. $ sudo npm install -g nodemon 모든 설치가 끝났다. 이제 nodejs를 실행시킬 프로젝트용 directory를 만든다. 이렇게 만들어 주고 express를 실행시키면 된다. $ express -e 다음과 같은 결과가 나오면 된다. 이제 node package를 설치하는 명령어를 입력하자. $ sudo npm install 이제 vi를 통해 포트번호를 정의해보자. app.set의 마지막에 한줄을 추가하면 된다. app.set('port', process.env.PORT || 9000); 이로써 우리는 9000번 포트를 사용하게 되었다. 또한 마지막줄에 서버를 생성하기 위한 코드를 작성하자. module.exports = app; var server = app.listen(app.get('port'), function() { console.log('Express server listening on port ' + server.address().port); }); 이...

20.03.24 ShareBook TIL

20.03.24 ShareBook TIL Project/TIL 20.03.24 ShareBook TIL 중간 배포를 위해 EC2, RDS를 다시 설정하였다. EC2에 git에서 clone을 하고 서버를 작동시켜보니 ts로 돌려서 그런지 작동하지 않고 대기 상태로 있다가 timeout같은 시간 초과 에러가 났다. 그리고 갑자기 EC2 자체가 느려져서 nodejs를 삭제하고 다시 nvm으로 높은 버전의 node를 설치하였다. 그리고 나서 혹시 js로 돌리면 될까 해서 tsc로 js로 변환한뒤 돌려보니 RDS와 연결이 되지 않는 에러가 생겼다. workbench로 RDS를 연결했을 때는 정상적으로 작동해서 EC2에서 잘 못 설정한게 있다고 생각했다. 그래서 local에서 한번 config.json을 수정하고 연결하여도 똑같은 에러가 발생했다. 그럼 보안 설정에서 문제인가 싶어서 EC2, RDS 보안 그룹에서 설정을 막 만져보다 RDS에서 Custom TCP에 처음 RDS에서 설정한 포트를 넣어주었더니 연결되었다. config.json내용을 EC2에도 똑같이 적용시켜보려고 json파일을 vim으로 작성해서 넣어 주었지만 여전히 같은 에러를 반복하였다. 그럼 json 파일을 못 읽어내는게 아닌가 싶어서 그냥 module에 index.js에서 sequelize를 생성하는 부분에 직접 넣어 주었더니 마침내 연결이 되었다. 해결하고 난 뒤 생각의 흐름을 적어보니 매우 짧지만 정작 오늘 아침 10시 반부터 시작해서 저녁 10시 반까지 12시간을 고민하고나서야 해결되었다. from http://three-five.tistory.com/46 by ccl(A) rewrite - 2020-03-25 00:54:05