|
| 1 | +import { EventEmitter } from 'events'; |
1 | 2 | import WebSocket from 'ws'; |
2 | 3 | import { Connection } from './connection'; |
3 | | -import { Stream } from './stream'; |
4 | 4 |
|
5 | | -const wss = new WebSocket.Server({ port: 8080 }); |
| 5 | +export interface LinkServerOptions extends WebSocket.ServerOptions { |
| 6 | + // You can add additional options here if needed, |
| 7 | + // for now we just extend standard WS server options |
| 8 | +} |
6 | 9 |
|
7 | | -console.log('WebSocket server started on port 8080'); |
| 10 | +export class LinkServer extends EventEmitter { |
| 11 | + private wss: WebSocket.Server; |
8 | 12 |
|
9 | | -wss.on('connection', (ws: WebSocket) => { |
10 | | - const connection = new Connection(ws); |
| 13 | + constructor(options: LinkServerOptions) { |
| 14 | + super(); |
| 15 | + this.wss = new WebSocket.Server(options); |
| 16 | + this.init(); |
| 17 | + } |
11 | 18 |
|
12 | | - connection.on('newStream', (stream: Stream) => { |
13 | | - console.log(`New stream created: ${stream.id} on connection ${connection.id}`); |
| 19 | + private init() { |
| 20 | + this.wss.on('connection', (ws: WebSocket) => { |
| 21 | + const connection = new Connection(ws); |
| 22 | + this.emit('connection', connection); |
| 23 | + }); |
14 | 24 |
|
15 | | - // Example: Echo back data |
16 | | - stream.on('data', (data: any) => { |
17 | | - console.log(`Received data on stream ${stream.id}:`, data); |
18 | | - // Echoing back |
19 | | - // stream.send({ echoed: data }); |
| 25 | + this.wss.on('error', (error) => { |
| 26 | + this.emit('error', error); |
20 | 27 | }); |
21 | 28 |
|
22 | | - stream.on('close', () => { |
23 | | - console.log(`Stream ${stream.id} closed`); |
| 29 | + this.wss.on('listening', () => { |
| 30 | + this.emit('listening'); |
24 | 31 | }); |
25 | | - }); |
| 32 | + } |
26 | 33 |
|
27 | | - connection.on('close', () => { |
28 | | - console.log(`Connection ${connection.id || 'unknown'} closed`); |
29 | | - }); |
30 | | -}); |
| 34 | + public close(cb?: (err?: Error) => void) { |
| 35 | + this.wss.close(cb); |
| 36 | + } |
| 37 | +} |
0 commit comments