forked from PrismarineJS/prismarine-web-client
-
Notifications
You must be signed in to change notification settings - Fork 65
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
import { EventEmitter } from 'events' | ||
import { Duplex } from 'stream' | ||
import states from 'minecraft-protocol/src/states' | ||
import { createClient } from 'minecraft-protocol' | ||
|
||
class CustomDuplex extends Duplex { | ||
constructor (options, public writeAction) { | ||
super(options) | ||
} | ||
|
||
override _read () {} | ||
|
||
override _write (chunk, encoding, callback) { | ||
this.writeAction(chunk) | ||
callback() | ||
} | ||
} | ||
|
||
export const getWsProtocolStream = async (url: string) => { | ||
if (url.startsWith(':')) url = `ws://localhost${url}` | ||
if (!url.startsWith('ws')) url = `ws://${url}` | ||
const ws = new WebSocket(url) | ||
await new Promise<void>((resolve, reject) => { | ||
ws.onopen = () => resolve() | ||
ws.onerror = reject | ||
ws.onclose = reject | ||
}) | ||
const clientDuplex = new CustomDuplex(undefined, data => { | ||
// console.log('send', Buffer.from(data).toString('hex')) | ||
ws.send(data) | ||
}) | ||
// todo use keep alive instead? | ||
let lastMessageTime = performance.now() | ||
ws.addEventListener('message', async (message) => { | ||
let { data } = message | ||
if (data instanceof Blob) { | ||
data = await data.arrayBuffer() | ||
} | ||
clientDuplex.push(Buffer.from(data)) | ||
lastMessageTime = performance.now() | ||
}) | ||
setInterval(() => { | ||
if (performance.now() - lastMessageTime > 10_000) { | ||
console.log('no packats received in 10s!') | ||
clientDuplex.end() | ||
} | ||
}, 5000) | ||
|
||
ws.addEventListener('close', () => { | ||
console.log('ws closed') | ||
clientDuplex.end() | ||
// bot.emit('end', 'Disconnected.') | ||
}) | ||
|
||
ws.addEventListener('error', err => { | ||
console.log('ws error', err) | ||
}) | ||
|
||
return clientDuplex | ||
} |