Websocket is not connecting with javascript - javascript

So i'm trying to connect to a websocket server using javascript. I tried doing this with NODEJS with the following code and it worked.
const WebSocket = require('ws');
const ws = new WebSocket('<Websocket Address>', {
origin: '<URL>'
});
ws.on('open', function open() {
ws.send(JSON.stringify({"event":"auth","args":["<My authentication token>"]}))
ws.send(JSON.stringify({"event":"send logs","args":[null]}))
console.log('connected');
});
ws.on('close', function close() {
console.log('disconnected');
});
ws.addEventListener('send logs', function (event) {
console.log('Message from server ', event);
});
ws.on('message', function incoming(data) {
console.log(data);
}, 500);
Is there a way I can write this in plain javascript? Like in script tags? I've read that the following code should work but it's giving me this error Uncaught DOMException: "An invalid or illegal string was specified"
const ws = new WebSocket('<Websocket address>', {
origin: '<URL>'
});
ws.on('open', function open() {
ws.send(JSON.stringify({"event":"auth","args":["<My authentication Token>"]}))
ws.send(JSON.stringify({"event":"send logs","args":[null]}))
console.log('connected');
});
ws.on('close', function close() {
console.log('disconnected');
});
ws.addEventListener('send logs', function (event) {
console.log('Message from server ', event);
});
ws.on('message', function incoming(data) {
console.log(data);
}, 500);
Could anyone tell me what i'm doing wrong?

Related

How to check consol.log and play sound in JavaScript

I am planning for queue system application using WebSocket ,PHP ,MySQL ,HTML to send console.log from one client to another to play sound for next queue ,
now I want to check in clinet2 if console.log value which I receive it client ='Hello From Client1!' paly sound or if = 'another message' do action.
Client1
<button onclick="sendMessage()">Send Msg</button>
</body>
<script>
// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:3000');
// Connection opened
socket.addEventListener('open', function (event) {
console.log('Connected to WS Server')
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
});
const sendMessage = () => {
socket.send('Hello From Client1!');
}
</script>
Client2
<button onclick="sendMessage()">Send Msg</button>
</body>
<script>
// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:3000');
// Connection opened
socket.addEventListener('open', function (event) {
console.log('Connected to WS Server')
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
});
const sendMessage = () => {
socket.send('Hello From Client2!');
}
</script>
Thanks All,
I think I got some code can help me.
I add in Client 1
<script>
var connection = new WebSocket ('ws://localhost:3000');
connection.onmessage = function (event){
document.getElementById("sul").value=event.data;
};
const sendMessage = () => {
socket.send("test");
}
</script>
<output type="text" id="sul" value="" readonly></output>
and client 2
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
if (event.data =='sul 1'){
console.log('Here i can put my play sound');
playsound();
}
});

Socket.io JS Client returning connection false

Im trying to connect the socket in my client js file but the response im getting is always false and no socket.on function is working
<script>
debugger
const socket = io.connect('http://localhost:5000');
console.log('check 1', socket.connected);
socket.on('connect', function () {
console.log('check 2', socket.connected);
});
socket.on("connect_error", (reason) => {
console.log('check 2', reason);
socket.connect();
});
socket.on('disconnect', function () {
console.log('check 2', socket.connected);
});
</script>
No function is running but looking at the network debugger it is returning 200 response . Any help would be apprecaited

NodeJS Cannot receive data from telnet socket after writing to it

when I connect I get the initial data as if I opened the telnet manually from the CMD, but I'm trying to send a command and it doesn't seem to be working as it's not logging the data. I looked everywhere and I'm not sure what to do.
Here is the code I used
const conn = new net.Socket();
conn.connect({port: 587, host: mxOrDomain}, () => {
conn.setEncoding('utf8');
conn.on('data', (data) => {
const message = data.toString();
console.log(message);
});
conn.on('error', (data) => {
console.log('error : ', data);
});
conn.on('drain', () => {
console.log('drained');
});
conn.on('end', () => {
console.log('Ended');
});
setTimeout(() => {
conn.write('HELO blahbalh.com\\r\\n', 'utf8');
}, 2000);
});
Also, is there a reason why telnet {domain} 587 works in CMD and not when using cp.exec() or .spawn() ?
Turns out you have to end your write string with \r\n but my IDE put \\r\\n by default.

PeerJS error when trying to call another peer: Failed to execute 'addStream' on 'RTCPeerConnection': parameter 1 is not of type 'MediaStream'

I am successfully establishing a connection between two peers using PeerJS but whenever I try passing a MediaStream object to the .call function I get this error:
Failed to execute 'addStream' on 'RTCPeerConnection': parameter 1 is
not of type 'MediaStream'
Everything else works great, connection is indeed established, both peers receive messages from each other via the 'open' event. The only thing that doesn't work is the peer.call() function. The microphone is properly captured after requesting the permission to do so.
Am I making some kind of a mistake here? I'd appreciate any help. Thank you.
Here is my code:
var media;
jQuery(document).ready(function() {
var peer = new Peer({
key: 'xxxxxxxxxxxxx'
});
media = navigator.mediaDevices.getUserMedia({
audio: true,
video: false
});
peer.on('open', function(id) {
console.log('My peer ID is: ' + id);
});
var conn = peer.connect(callID);
conn.on('open', function() {
// Receive messages
conn.on('data', function(data) {
console.log('Received', data);
});
// Send messages
conn.send('Hello!');
});
console.log(typeof(media));
var call = peer.call(callID, media);
peer.on('error', function(err) {
console.log(err);
});
});
I'd be interested to see the output of console.log(typeof(media));.
According to the MDN website, it seems that the following line will return a Promise instead of a MediaStream:
media = navigator.mediaDevices.getUserMedia({audio: true, video: false});
The following should work:
var media;
jQuery(document).ready(function() {
var peer = new Peer({
key: 'xxxxxxxxxxxxx'
});
navigator.mediaDevices.getUserMedia({
audio: true,
video: false
})
.then(function(mediaStream) {
peer.on('open', function(id) {
console.log('My peer ID is: ' + id);
});
var conn = peer.connect(callID);
conn.on('open', function() {
// Receive messages
conn.on('data', function(data) {
console.log('Received', data);
});
// Send messages
conn.send('Hello!');
});
console.log(typeof(media));
var call = peer.call(callID, mediaStream);
peer.on('error', function(err) {
console.log(err);
});
});
});

Send event to client, from server, and then disconnect the socket (from server)

I want to send an event back to a client, in Socket.io, and immediately after that to disconnect the client. The problem is that calling socket.emit() will not emit anything...
Do you know, or stepped into this kind of problem?
my code is like this:
- on server:
userCredentialsCheck: function (socket, next, callback) {
appLogSys.info('Check cookie!');
.....
var handshake = socket.request;
.....
parseCookie(handshake, null, function (err, data) {
sessionSrv.get(handshake, function (err, session) {
if (err) {
appLogSys.error(err.message);
next(new Error(err.message));
}
else
{
......
socket.emit('na', 'Error checking session! Good bye!');
socket.disconnect();
}
})
})
};
on client:
appSocket.on('na', function(d){
console.log('Error: '+d);
console.log('Now, redirect!');
//REDIRECT!
var delay = 1000; //Your delay in milliseconds
var URL = '/';
setTimeout(function(){ window.location = URL; }, delay);
});
Thank you!

Categories

Resources