ws.message is undefined Error, Web Socket response - javascript

I am python developer but i need to see my websocket output from browser.
function startSocket() {
var ws = new WebSocket("ws://localhost:8765/")
ws.onopen = function(event) {
ws.send("Sent this from client.js")
console.log(typeof ws.message);
console.log("test")
console.log(ws.message)
}
}
startSocket();
this is my clien.js file.
<!DOCTYPE html><html lang="en">
<head>
<!-- <link rel="stylesheet" type="text/css" href="style.css">-->
<link type="text/css" href="styles.css">
<meta charset="utf-8">
</head>
<body>
<script src="client.js"></script>
</body></html>
and this is my html file.
I am sending a string from my web socket and i want to see inside of a browser.
When i run this html, my web socket is starting to work but my logs are saying undefined.
This is my Log Output
client.js:6 undefined
client.js:7 test
client.js:8 undefined

read more here
bind to the correct event handlers
function startSocket() {
var ws = new WebSocket("ws://localhost:8765/");
ws.onopen = function(event) {
console.log("connection opened");
ws.send("Sent this from client.js")
};
ws.onmessage = function(message) {
console.log(typeof message);
console.log("test")
console.log(message)
};
};
startSocket();

Related

socket.io console.log(userName) not showing in the command line

I'm creating a chat application using socket.io, so basically what I'm trying is to console.log the user who joined the chat, here I'm taking a prompt from the client and emitting to the server, but cannot find any log in my command line. And on top I'm getting this error ERR_NAME_NOT_RESOLVED.
ERR_NAME_NOT_RESOLVED img
Index Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>See-me</title>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script src="js/client.js"></script>
<link rel="stylesheet" href="css/styles.css">
<link rel = "icon" href ="logo/appIcon.ico" type = "image/x-icon">
</head>
<body>
</body>
</html>
Client Side Js:
const socket = io('http//localhost:3000')
const form = document.getElementById('send-container')
const messageInput = document.getElementById('messageImp')
const messageContainer = document.querySelector(".container")
const userName = prompt("Enter your Name to join");
socket.emit('new-user-joined', userName)
Server Side JS:
const io = require('socket.io')(3000)
const users = {};
io.on('connection', (socket) => {
socket.on('new-user-joined', userName =>{
console.log("New user", userName);
users[socket.id] = userName;
socket.broadcast.emit('user-joined', userName)
});
socket.on('send', message => {
socket.broadcast.emit('receive', {message: message, userName: users[socket.id]})
});
})
All I want is to console log the user who joined the chat.
The error is actually pointing to what the issue is:
const socket = io('http//localhost:3000')
That URL is missing a colon after http

How does connect and disconnect work with Sockets

I began learning sockets today and I have some questions about how it works. I'm using flask_socketIO and this is the code I found in a tutorial
Main.py
from flask import Flask
from flask_socketio import SocketIO, send
app = Flask(__name__)
app.config["SECRET_KEY"] = "secret"
socketio = SocketIO(app, cors_allowed_origins="*")
#socketio.on("message")
def handleMessage(msg):
print("Message: " + msg)
send(msg, broadcast=True)
if __name__ == "__main__":
socketio.run(app)
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Chat room</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.0/socket.io.js"
integrity="sha512-/xb5+PNOA079FJkngKI2jvID5lyiqdHXaUUcfmzE0X0BdpkgzIWHC59LOG90a2jDcOyRsd1luOr24UCCAG8NNw=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(() => {
var socket = io.connect("http://127.0.0.1:5000");
socket.on("connect", () => {
socket.send("User has connected!");
});
socket.once("disconnect", () => {
socket.send("User has disconnected!");
console.log("User Disconnected");
});
socket.on("message", (msg) => {
$("#messages").append("<li>" + msg + "</li>");
console.log("Message recieved");
});
$("#sendButton").on("click", () => {
socket.send($("#myMessage").val());
$("#myMessage").val("");
});
});
</script>
<ul id="messages"></ul>
<input type="text" id="myMessage" />
<button id="sendButton">Send</button>
</body>
</html>
I understand how message works but I don't understand how the connect and disconnect events work. When a new user goes on the page, it logs out both in terminal and on website"User has connected". Why does it do that even though I don't have print() for my terminal or a function similar to
$("#sendButton").on("click", () => {
socket.send($("#myMessage").val());
$("#myMessage").val("");
});
for the website. Also disconnect doesn't work at all, it doesn't console.log when a user disconnects. Does anyone know why?
When a new user goes on the page, it logs out both in terminal and on website"User has connected". Why does it do that even though I don't have print() for my terminal or a function similar to
The browser sends it to the the server. The server prints it (in the server's terminal) and also sends it to all the connected browsers, which log it in #messages.
Also disconnect doesn't work at all, it doesn't console.log when a user disconnects. Does anyone know why?
After the browser disconnects the browser tries to send the message to the server. The server never gets it because the browser already disconnected. Possibly the browser throws an exception when you try to send to a disconnected socket and so it never gets to the next line of code which calls console.log.

How to emit a result from javascript code to all users connected using socket.io

I saw this js code online and i modified the best my knowledge to make it not only visible to current user but all users:
var textarea = $('#textarea');
var typingStatus = document.querySelector('#typing_on');
var lastTypedTime = new Date(0); // it's 01/01/1970
var typingDelayMillis = 2000; // how long user can "think about his spelling" before we show "No one is typing -blank space." message
function refreshTypingStatus() {
if (!textarea.is(':focus') || textarea.val() == '' || new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) {
socket.emit('stat', typingStatus.innerHTML = 'no type');
} else {
socket.emit('stat', typingStatus.innerHTML = 'User typing....');
}
}
function updateLastTypedTime() {
lastTypedTime = new Date();
}
setInterval(refreshTypingStatus, 100);
textarea.keypress(updateLastTypedTime);
textarea.blur(refreshTypingStatus);
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylesheet" type="text/css" href="styles2.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input name="textarea" id="textarea" cols="45" rows="5">
<div id="typing_on"></div>
</body>
What i did in front end is add socket.emit to the result as seen above and i did equivalent to that in back-end (server.js)
but it doens't work and show like this:
what i want is for the 'user typing' to appear in both sides (clients)
How can i do that?
To send message from client to server and then sending the message to all clients connected to the websocket:
server.js
io.on('connect', socket => {
let counter = 0;
setInterval(() => {
socket.emit('hello', ++counter);
}, 1000);
});
Index.html
const socket = io();
socket.on('connect', () => {
$events.appendChild(newItem('connect'));
});
socket.on('hello', (counter) => {
$events.appendChild(newItem(`hello - ${counter}`));
});
If you want to send message to all clients except the person who is sending the message, use broadcast instead of emit

WebSocket Error on Android Device, Works in IE

I have an issue with a websocket client.
It seems to work fine in IE and Edge. The server responds with a message and the client receives and displays this message, but when my android device runs this code, the error handler gets fired off and the connection is closed immediately.
The error handler gives me a message: "undefined"
Here is my Client:
<!DOCTYPE html>
<html>
<head>
<title>HTML5 Touch Tracing </title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script type='text/javascript'>
function openSocket(){
if ("WebSocket" in window)
{
alert("WebSocket is supported by your Browser!");
//var WebSocket = require('ws');
var ws = new WebSocket("ws://localhost:8080/WebSocketServer/control");
ws.onopen = function ()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Message = " + received_msg);
};
ws.onclose = function ()
{
// websocket is closed.
alert("Connection is closed...");
};
ws.onerror = function(evt)
{
alert("Error: " + evt.data);
};
} else
{
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<meta name="viewport" content="width=device-width,user-scalable=no">
<div>
Keyboard
</div>
</body>
</html>
My Server simply just responds with a message:
#OnMessage
public String onMessage(String message) {
return "Got it.";
}

Node.js socket.io with websocket

I'm begginer in Node.js or websocket. I have problem:
My HTML code:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
"use strict";
var gniazdo = new WebSocket('ws://localhost:3000');
gniazdo.onopen = function(){
console.log('Połączono');
};
gniazdo.onmessage = function(m){
console.log(m.data);
};
</script>
</body>
</html>
My Node.js code:
var io = require('socket.io')(3000);
io.on('connection', function(socket){
console.log('a user connected');
});
I have error in console:
WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response
Help plz :)
Your client is using WebSockets, but Socket.IO has its own protocol (that may be transported over WebSockets, but it can also be transported over other protocols). Change your client to use Socket.IO's own client:
<script src="https://cdn.socket.io/socket.io-1.1.0.js"></script>
<script>
'use strict';
var gniazdo = io('ws://localhost:3000');
gniazdo.on('connect', function () {
console.log('Połączono');
gniazdo.on('message', function (m) {
console.log(m.data);
});
});
</script>

Categories

Resources