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 1 commit
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
Next Next commit
add webSocket example
  • Loading branch information
Mert Can Altin committed Jan 18, 2024
commit febd70e8d4cb0acc381821fb3a843a62193b1ffc
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 @@
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 @@
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!');

Check failure on line 75 in examples/proxy/index.js

View workflow job for this annotation

GitHub Actions / lint

Extra semicolon
});

Check failure on line 76 in examples/proxy/index.js

View workflow job for this annotation

GitHub Actions / lint

Extra semicolon

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

Check failure on line 80 in examples/proxy/index.js

View workflow job for this annotation

GitHub Actions / lint

Extra semicolon
});

Check failure on line 81 in examples/proxy/index.js

View workflow job for this annotation

GitHub Actions / lint

Extra semicolon
}

run()

// TODO: Add websocket example.
Loading