I am trying to set up a basic chat app with node.js/express/socket.io but for some reason when the client sends message (this works, another client will get the message) it also refreshes the client and the url goes from localhost:3000 to localhost:3000/? (adds /? to end, i don't know what this means). I cant find anything wrong in my code after looking at it for hours. I have:
server.js:
let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
let port = process.env.PORT || 3000;
app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html') });
http.listen(port,() => { console.log('listening on *:' + port) });
io.on('connection', socket => {
socket.on('chat', text => {
io.sockets.emit('chat', `<p>${text}</p>`);
});
});
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<style>
.chat_view{
height: 300px;
width: 200px;
border: 5px ridge black;
overflow-y: scroll;
}
</style>
</head>
<body>
<div class="chat" id="chat">
<div class="chat_view" id="chat_view">
</div>
<form id="chat_form">
<input type="text" title="chat_input" id="chat_input" style="width: 206px">
</form>
</div>
<script>
let socket = io();
$('#chat_form').submit( () => {
let text = $('#chat_input').val();
socket.emit('chat', text);
});
socket.on('chat', text => {
let chat_view = document.getElementById('chat_view');
chat_view.innerHTML += text;
chat_view.scrollTop = chat_view.scrollHeight;
});
</script>
</body>
</html>
and package.json:
{
"name": "RatScrew",
"version": "0.0.1",
"dependencies": {
"express": "^4.15.3",
"socket.io": "^2.0.2"
}
}
If you're listening to the submit event, that means the form will actually try and POST to the server (which will in your case refresh the screen). If you're using JavaScript to communicate with the server and don't need the form data to get posted by the browser directly, just return false from your callback. Some browsers also want you to call e.preventDefault() as well.
Change your code to:
$('#chat_form').submit((event)=>{
event.preventDefault();
let text = $('#chat_input').val();
socket.emit('chat', text);
});
The default method used when submiting the form is the GET method, which makes the server send index.html again and the page refreshes.
You may want to have a look at https://www.w3.org/TR/html401/interact/forms.html
Related
im trying to implement a chat client, i think my client server communication work, because i receive the messages in different tabs. im using a https connection
im getting in chrome following error:
WebSocket connection to 'wss://localhost/socket.io/?EIO=4&transport=websocket&sid=B-vRFkxNxHPkiK6cAAAE' failed: websocket.js:54
in firefox:
Firefox can’t establish a connection to the server at wss://localhost/socket.io/?EIO=4&transport=websocket&sid=vSwzZh9BE3cpHZHPAAAC.
im using a self signed certificate, that i created with openssl, thats why i get follwing konsole log in chrome:
This site does not have a valid SSL certificate! Without SSL, your site's and visitors' data is vulnerable to theft and tampering. Get a valid SSL certificate before releasing your website to the public.
server.js:
const express= require('express')
const app= express();
const https= require('https')
const fs=require('fs')
const PORT=process.env.PORT || 443
const httpsOptions={
key: fs.readFileSync('cert/key.pem'),
cert: fs.readFileSync('cert/cert.pem')
}
var server=https.createServer(httpsOptions,app);
server.listen(PORT,function(){
console.log(`listening to port ${PORT}`)
})
const io = require('socket.io')(server,{maxHttpBufferSize:1e8}).listen(server)
app.get('/test', (req,res)=>{
res.sendStatus(200);
})
app.use(express.static(__dirname + '/public'))
app.use(require('./routes/posts'));
app.use(require('./routes/users'));
//app.use(require('./public/client'));
app.get('/',(req,res)=>{
res.sendFile(__dirname + '/login_register/login.html')
})
app.get('/register',(req,res)=>{
res.sendFile(__dirname + '/login_register/register.html')
})
app.get('/chatroom',(req,res)=>{
res.sendFile(__dirname + '/index.html')
})
io.on('connection',(socket)=>{
console.log('new connection',socket.id)
socket.on('message', (msg)=>{
socket.broadcast.emit('message',msg)
})
socket.on('file-message', (msg)=>{
socket.broadcast.emit('file-message',msg)
})
})
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>Document</title>
<link rel="stylesheet" href="/style.css">
<script src="https://cdn.socket.io/4.4.1/socket.io.min.js" integrity="sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H" crossorigin="anonymous"></script>
</head>
<body>
<section class="chat_section">
<div class="brand">
<img src="" alt="">
<h1> chat</h1>
</div>
<div class="message_area">
</div>
<div>
<textarea id="textarea" cols="30" rows="1" placeholder="write a message "></textarea>
</div>
<input type="file"id="fileupload" name="fileName">
<button id="submitFile" onclick="submitData()">senden</button>
</section>
<script>
socket = io('https://localhost:443/')
//also testet:
//const socket=io()
//didnt worked
let userName;
let userName_;
//const textarea = document.getElementById('textarea')
let textarea=document.querySelector('#textarea')
let messageArea= document.querySelector('.message_area')
let file__ = document.querySelector('#fileupload')
userName=sessionStorage.getItem('displayUsername')
userName_= userName
console.log(userName_)
sessionStorage.removeItem('displayUsername');
sessionStorage.clear();
//console.log(userName_)
if(userName_==null){
alert("dont scam")
window.location.href = '/'
}
//console.log(localStorage.getItem(displayUsername));
textarea.addEventListener('keyup', (e)=>{
if(e.key === 'Enter'){
sendMessage(e.target.value)
}
})
function sendMessage(message){
let msg= {
user:userName_,
message:message.trim()
}
//append message to frontend call function
appendMessage(msg,'outgoing')
textarea.value=""
scrollBottom()
//send to server
socket.emit('message', msg)
}
function appendMessage(msg,type,isFile){
//dont needed to understand
}
//recive messages
socket.on('message',(msg)=>{
//console.log(msg)
appendMessage(msg,'incoming')
scrollBottom()
})
socket.on('file-message',(msg)=>{
console.log(msg)
//File name Here
let message={
message: msg.filename,
user: msg.user,
result: msg.result
}
//send to the others
appendMessage(message,'incoming',isFile=true)
})
function scrollBottom(){
messageArea.scrollTop=messageArea.scrollHeight
}
function submitData(){
//dont needed to understand
}
}
function downloadFile(result,filename){
//dont needed to understand
}
</script>
</body>
</html>
I am learning to use node.js on a public server as a open line from server to clients (https://github.com/iamshaunjp/websockets-playlist/tree/lesson-5).
I have done a youtube tutorial to create a chat server / client. This works on my own machine.
The server code (index.js):
var express = require('express');
var socket = require('socket.io');
// App setup
var app = express();
var server = app.listen(4000, function () {
console.log('listening to request on port 4000');
})
// Static files
app.use(express.static('public'));
// Socket setup
var io = socket(server);
io.on('connection', function (socket) {
console.log('made socket connection', socket.id);
socket.on('chat', function (data) {
io.sockets.emit('chat', data);
});
socket.on('typing', function (data) {
socket.broadcast.emit('typing', data);
});
});
The browser code (/public/chat.js):
// Make connection
var socket = io.connect('http://localhost:4000');
// Query DOM
var message = document.getElementById('message');
var handle = document.getElementById('handle');
var btn = document.getElementById('send');
var output = document.getElementById('output');
var feedback = document.getElementById('feedback');
// Emit events
btn.addEventListener('click', function () {
socket.emit('chat', {
message: message.value,
handle: handle.value
});
});
message.addEventListener('keypress', function () {
socket.emit('typing', handle.value);
});
// Listen for events
socket.on('chat', function (data) {
feedback.innerHTML = '';
output.innerHTML += '<p><strong>' + data.handle + ':</strong>' + data.message + '</p>';
});
socket.on('typing', function (data) {
feedback.innerHTML = '<p><em>' + data + ' is typing a message...</em></p>';
});
The browser code (public/index.html):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Websockets 101</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<link href="/styles.css" rel="stylesheet" />
</head>
<body>
<div id="mario-chat">
<div id="chat-window">
<div id="output"></div>
<div id="feedback"></div>
</div>
<input id="handle" type="text" placeholder="Name" />
<input id="message" type="text" placeholder="Message" />
<button id="send">Send</button>
</div>
<script src="/chat.js"></script>
</body>
</html>
When i go to http://localhost:4000 i see the chat screen and i can chat (to multiple browser windows).
now i want to upload my code to the ubuntu development server but i can't get it working. I have installed Node.js on the server and when i type node -v i get the version number so the installation is correct.
What is my next step? If i upload the code to the development server (http://devserver01/websocket/) it won't display my code because i don't have an index.html.
On the localhost i have used this code (package.json):
{
"name": "websocket",
"version": "1.0.0",
"description": "websocket",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"socket.io": "^2.3.0"
},
}
If i go to http://devserver01/websocket/ it doesnt work (ofcourse), but also http://devserver01:4000 doesn't work (also ofcourse because it can't know it has to go to the js file).
But i cannot find any information on how to deploy this on a remote linux machine.
Thank you for the help!
So I have a socket-io script on my client side that just do the simple task of connecting to a server. So far , so good.
What I am trying to do is to load the javascript script containing socket.io ONLY when a button is clicked by the user and not when the page is parsed by the browser.
Here is the client.html :
<html>
<head>
<meta charset="utf-8" />
<title>Socket.io</title>
</head>
<body>
<h1>Communicating with socket .io!</h1>
<div>
<form>
<input id="wawa" type="text" name="firstname" value="">
<button onclick="get_data()">Send data to server</button>
</form>
</div>
<script src="socket-io.js"></script>
<script>
let socket = io.connect('http://localhost:5000');
function get_data() {
socket.on('connect', function() {
console.log('Connected to the server');
});
}
</script>
</body>
</html>
server.js if it might help ?
let io = require('socket.io').listen(process.env.port||5000);
io.on('connection', function(socket) {
console.log('New client connected');
socket.on('wawa',function (data) {
console.log(`data received is '${data}'`);
});
Basically , I do not was the JS script to load when the page is parsed but to load only when a button is clicked.
How can I achieve this ?
In you JavaScript area on the HTML file you can do this:
<script>
var socket;
function loadSocket() {
socket = io.connect('http://localhost:5000');
}
function get_data() {
socket.on('connect', function() {
console.log('Connected to the server');
});
}
</script>
In your HTML code you can have a button to call the loadSocket:
<button onclick="loadSocket();">Connect</button>
js code. which is a server file
while i am running this below code it is not sending messages when i click the button.
var express = require('express');
var socket = require('socket.io');
var app = express();
var server = app.listen(8000,function(){
console.log("The server is listening on the port 8000");
});
app.use(express.static('public'));
var io = socket(server);
io.on('connection', function(socket){
socket.on("chat", function(data){
io.sockets.emit("chat", data);
});
});
here is my index.html code which also contains
and css file which i am not included here
<!DOCTYPE html>
<html>
<head>
<title>my first chat app</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js">
</script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="mario-chat">
<div id="chat-window">
<div id="output"></div>
<div id="feedback"></div>
</div>
<input id="handle" type="text" placeholder="Handle"/>
<input id="message" type="message" placeholder="Message"/>
<button id="send">Send</button>
</div>
<script src="/chat.js"></script>
</body>
</html>
the above code include a stylesheet.css file for looking good.
here is my chat.js file which is client side functionalities.
var socket = io.connect("http://localhost:8000");
var message = document.getElementById("message");
var handle = document.getElementById("handle");
var btn = document.getElementById("send");
var output = document.getElementById("output");
var feedback = document.getElementById("feedback");
btn.addEventListener("click",function(){
socket.emit("chat", {message:message.value,handle:handle.value});
});
socket.on("chat", function(data){
output.innerHTML += '<p><strong>' + data.handle + ':</strong>' +
data.message + '</p>';
});
please rectify me where i am doing mistakes
thanks in advance.
In your client code socket must be created with ws protocol. So,
io.connect("http://localhost:8000"); should be io.connect("ws://localhost:8000");
I'm starting playing with node.js and as everybody, I want do a chat.
My idea is run node.js with socket.io in the port 9090, for example, and my client html in the port 8080. My html client will be served independent.
My server:
var sys = require('sys');
var express = require('express');
var io = require('socket.io');
var app = express.createServer();
app.listen(8080);
var socket = io.listen(app);
socket.on('connection', function (client) {
client.on('message', function (msg) {
socket.broadcast(msg);
});
client.on('disconnect', function () {
});
});
My client:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
<script>
$(document).ready(function () {
var socket = new io.Socket("localhost", {port: 8080});
socket.on('connect', function () {
socket.send('A client connected.');
});
socket.on('message', function (message) {
$('div#messages').append($('<p>'), message);
});
socket.on('disconnect', function () {
console.log('disconnected');
});
socket.connect();
$('input').keydown(function (event) {
if(event.keyCode === 13) {
socket.send($('input').val());
$('input').val('');
}
});
});
</script>
</head>
<body>
<input type="text" style="width: 300px;" />
<div id="messages" style="border:solid 1px #000;"> </div>
</body>
</html>
I'm running in ubuntu 11.04 with node.js v0.4.10.
The server works fine, but the client can't do connection, in the console.log on google Chrome I received this message:
XMLHttpRequest cannot load http://localhost:8080/socket.io/xhr-polling//1311465961485. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
The server.js is in a folder in /var/www/cliente/chat/public.
What's the problem?
Your client code is not actually being served from port 8080 as you want.
var sys = require('sys');
var express = require('express');
var io = require('socket.io');
var app = express.createServer();
app.listen(8080);
app.use(express.static(__dirname));
app.get('/', function(req, res){
res.render('index.html', { title: 'Chat' });
});
var socket = io.listen(app);
socket.on('connection', function (client) {
client.on('message', function (msg) {
socket.broadcast(msg);
});
client.on('disconnect', function () {
});
});
This should fix your Access-Control-Allow-Origin errors. Execute node server.js and connect to http://localhost:8080. A couple additional notes:
Make sure you have installed socket.io 0.6.x since that's what you are including in your html file. 0.7.x is backwards incompatible.
With this configuration you'll be running socket.io on the same port you are serving your page from (as opposed to 9090).
When I updated my client to:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script>
var socket = io.connect("http://localhost", {port: 8080});
socket.on('connect', function () {
socket.send('A client connected.');
});
socket.on('message', function (msg) {
$('div#messages').append($('<p>'), msg);
});
socket.on('disconnect', function () {
console.log('disconnected');
});
$(document).ready(function(){
$('#btn_send').click(function (event) {
socket.send($('#txt_msg').val());
$('#txt_msg').val('');
});
});
</script>
</head>
<body>
<input type="text" id="txt_msg" style="width: 300px;" /><input type="button" id="btn_send" value="send" />
<div id="messages" style="border:solid 1px #000;"> </div>
</body>
</html>
Everything worked.
I was using a version 0.7 of the socket.io that was the problem: https://github.com/LearnBoost/Socket.IO/wiki/Migrating-0.6-to-0.7
You cannot make AJAX requests to URLs that are not on the same hostname and port as the current page. It's a security restriction in all web browsers.