Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add webSocket example #2626

Merged
merged 5 commits into from
Jan 26, 2024
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions examples/proxy/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const { Pool, Client } = require('../../')
const http = require('http')
const proxy = require('./proxy')
const WebSocket = require('ws')

const pool = new Pool('http://localhost:4001', {
connections: 256,
Expand Down Expand Up @@ -30,6 +31,31 @@ async function run () {
http.createServer((req, res) => {
res.end('hello world')
}).listen(4001, resolve)
}),
new Promise(resolve => {
// WebSocket server
const wss = new WebSocket.Server({ noServer: true })
wss.on('connection', ws => {
ws.on('message', message => {
console.log(`Received message: ${message}`)
ws.send('Received your message!')
})
})

// Create an HTTP server to upgrade the connection to WebSocket
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('WebSocket server is running!')
})

// Upgrade HTTP server to support WebSocket
server.on('upgrade', (request, socket, head) => {
wss.handleUpgrade(request, socket, head, ws => {
wss.emit('connection', ws, request)
})
})

server.listen(4002, resolve)
})
])

Expand All @@ -42,8 +68,17 @@ async function run () {
for await (const chunk of body) {
console.log(String(chunk))
}

// WebSocket client
const ws = new WebSocket('ws://localhost:4002')
ws.on('open', () => {
ws.send('Hello, WebSocket Server!')
})

ws.on('message', message => {
console.log(`WebSocket Server says: ${message}`)
ws.close()
})
}

run()

// TODO: Add websocket example.
Loading