webSocket.onopen = () => {
console.log(‘WebSocket Client Connected’);
webSocket.send('Hi this is web client.');
};
webSocket.onmessage = (e) => {
console.log(‘Received: ’ + e.data);
};
webSocket.close = () => {
console.log('WebSocket Client Closed.’);
};
async getNewMsgObj(newMsgObj) {
let selectedUserChatId = this.getSelectedUserChatId()
let msgToSend = { chatId: selectedUserChatId, senderid: this.props.loggedInUserObj._id, receiverid: this.state.messageToUser._id, ...newMsgObj }
// Send Message for Encryption to Signal Protocol, then send the Encrypted Message to main server
try {
let encryptedMessage = await this.props.signalProtocolManagerUser.encryptMessageAsync(this.state.messageToUser._id, newMsgObj.message);
msgToSend.message = encryptedMessage
this.state.ws.send(JSON.stringify(msgToSend))
this.setState({ lastSentMessage: newMsgObj.message }) // Storing last-sent message for Verification with Received Message
} catch (error) {
console.log(error);
}
}
ws.onmessage = async (e) => {
let newMessage = JSON.parse(e.data)
// In case message is from self, save state-stored message to Chats i.e. no need of using/decrypting the received message
// This is only for verifying that the messages have successfully been received.
if (newMessage.senderid === this.props.loggedInUserObj._id) {
newMessage.message = this.state.lastSentMessage
} else { // Otherwise decrypt it and then save to Chats
// Decryption using Signal Protocol
let decrytedMessage = await this.props.signalProtocolManagerUser.decryptMessageAsync(newMessage.senderid, newMessage.message)
newMessage.message = decrytedMessage
}
}