add socket code
This commit is contained in:
parent
c9f8ea6337
commit
5a72970f34
3 changed files with 59 additions and 67 deletions
42
src/background/session.ts
Normal file
42
src/background/session.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import WebSocket from 'ws';
|
||||
import { windowEmitter } from './windowEmitter';
|
||||
|
||||
const ip = 'ws://localhost';
|
||||
const port = 8080;
|
||||
const username = 'hernandeze2@xavier.edu';
|
||||
|
||||
const receiveMessage = (message: string): void => {
|
||||
// NOTE assuming message is JSON string
|
||||
const parsed = JSON.parse(message);
|
||||
windowEmitter.emit('ipc-renderer', {
|
||||
endpoint: 'render-message',
|
||||
message: parsed
|
||||
});
|
||||
}
|
||||
|
||||
let socket: WebSocket;
|
||||
|
||||
export function initSession() {
|
||||
|
||||
try {
|
||||
socket = new WebSocket(`${ip}:${port}`);
|
||||
socket.binaryType = 'arraybuffer';
|
||||
|
||||
socket.on('open', () => {
|
||||
socket.send(username);
|
||||
})
|
||||
|
||||
socket.on("message", receiveMessage);
|
||||
|
||||
} catch(e) {
|
||||
console.log('error connecting socket', + e);
|
||||
}
|
||||
}
|
||||
|
||||
export const sendMessage = (content: string | Buffer) => {
|
||||
if (content instanceof Buffer) {
|
||||
socket.send(content);
|
||||
} else {
|
||||
socket.send(JSON.stringify(content));
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue