I am using sockets to send a file. On the server side I am listening to stream from the client side, but from the client side, I am not able to send data in chunks which can be sent to the server side.
I used FileReader to read the file in slices can you please tell what is that I am doing wrong?
Client Code
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Echo server</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<h1>File Upload</h1>
<form id="form" id="chat_form">
<input type="file" id="file_input" />
<input type="button" onclick="submit1()" value="submit">
</form>
<script src="socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io('localhost:8080');
var fReader;
socket.on('echo', function (data) {
console.log(data);
});
socket.emit('echo', 'this is a message');
function submit1() {
var file = $("#file_input")[0].files[0];
var reader = new FileReader();
reader.onload = function (evnt) {
socket.emit('join', { 'Name': Name, Data: evnt.target.result });
}
reader.readAsArrayBuffer(file);
}
</script>
</body>
</head>
SERVER code
var http = require('http')
var fs = require('fs');
var express = require('express')
var socketio = require('socket.io')
var app = express(server)
var server = http.Server(app)
var io = socketio(server)
app.get('/', function(req, res){
res.sendFile(__dirname + '/client.html')
});
io.on('connection', function(socket){
var writeStream = fs.createWriteStream(__dirname +'/m.png');
socket.on('echo', function(data){
socket.emit('echo', data);
});
socket.on('join', function(chunk){
console.log(chunk, "==============chunk=====================");
writeStream.write(chunk);
})
});
You never give the file object to your FileReader object. In fact, you never do anything with it so the FileReader object never has anything to do. For example, you may want to do:
reader.readAsArrayBuffer(file);
It also doesn't look like you're getting the data from the reader object correctly. There's a code examples here: File upload with socket.io and Send Images through Websockets.
Related
I'm still relatively new to node.js, so I decided to practice with a simple program.
I made this program to test the connectivity between the client and the server using node.js, express and socket.io.
This is my server.js
// Create an http server with Node's HTTP module.
const http = require('http');
// Create a new Express application
const express = require('express');
const app = express();
const clientPath = `${__dirname}/../client`;
console.log(`Serving static from ${clientPath}`);
app.use(express.static(clientPath));
const socketio = require('socket.io');
// Pass the http server the Express application
const server = http.createServer(app);
const io = socketio(server);
io.on('connection', function (socket) {
console.log("There's been a connection");
socket.on("console output", function (input) {
console.log(input)
});
socket.on("text alter", function(data){
var display = "'" + data + "' An interesting set of characters";
io.sockets.emit("display string", display);
})
})
//Listen on port 8080
server.listen(8080, function () {
console.log("Listening on port 8080");
})
This is my index.js
const socket = io();
let players = [];
function serverOutput(){
socket.emit("console output", "You suck at programming");
}
function serverAlter(){
const alterInput = document.querySelector('#userinput1').value;
socket.emit("text alter", alterInput);
}
socket.on("display string", function(){
const outputArea = document.querySelector('#outputspace1');
var fullLine = document.createElement("p");
outputArea.appendChild(fullLine);
})
Lastly my index.html
<html lang="en">
<head>
<title>Home</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="main-menu" class="page-templates">
<h3>Part 1: Press the button to see the server send a message</h3>
<button onclick="serverOutput()">Server message</button>
<br>
<h3>Part 2: Type in a string, and the server will add to it</h3>
<input type="text" id="userinput1">
<div id="outputspace1">
</div>
<button onclick="serverAlter()">Create sentence</button>
<script src="/socket.io/socket.io.js"></script>
<script src="src/index.js"></script>
</body>
</html>
From how the code runs, the server is able to pick up the data from the client, but when I try to change the data and send it back, the paragraph that is meant to be outputting the string has no data. I have a feeling I implemented the "io.sockets.emit()" incorrectly, but please if you guys can enlighten me, I would be so grateful.
In the client code, when you add data to your #outputspace1 element with this:
socket.on("display string", function(){
const outputArea = document.querySelector('#outputspace1');
var fullLine = document.createElement("p");
outputArea.appendChild(fullLine);
});
All you are doing there is adding an empty <p></p> element to #outputspace1. Instead, you need to capture the data being sent back to you by declaring the right incoming function parameter on your .on() event handler and then you need to add that data to the p element you created like this:
socket.on("display string", function(newText){
const outputArea = document.querySelector('#outputspace1');
var fullLine = document.createElement("p");
fullLine.innerHTML = newText;
outputArea.appendChild(fullLine);
});
This is my server side code for creating connection to the socket.I am using node.js code and using socket.io in that.
const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');
const port = process.env.PORT || 3000;
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
io.on('connection', (socket) => {
console.log('New user connected');
})
and this is my client side code i am using plain javascript as a client and I am using 2.1.1 version of socket.io, I am getting io not defiend error,I am very new to socket.io please help me one this one.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
</head>
<body>
<script>
$(document).ready(function(){
var socket = io('http://localhost:3000');
console.log("Socket connected"+socket.connected);
socket.on('notification', function(value){
//insert your code here
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
</body>
</html>
Your first script (the one using io) is running before your other scripts (the jQuery and Socket scripts). Move your scripts around like so:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script>
$(document).ready(function() {
var socket = io('http://localhost:3000');
console.log("Socket connected" + socket.connected);
socket.on('notification', function(value) {
//insert your code here
});
});
</script>
As I'm new to web development this might be wrong, but I would try to place your script below the script where you import socket.io.js
In your function you are calling io but before you call it it doesn't seem to be declared.
Hope this works.
Unresolved function or method get().
I'm new in js and node and I got stuck with this while trying to make a chat using sockets. Here is the code:
.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
server.listen(8888);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.on('send message', function (data) {
io.sockets.emit('new message', data);
});
});
.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>glupi chat</title>
<style>
#chat{
height: 500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message">
<input type="submit">
</form>
<script src='jquery-3.2.1.js'></script>
<script src="/socket.io/socket.io.js"></script>
<script>
$document.ready(function () {
var socket = io.connect();
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.submit(function (e) {
e.preventDefault();
socket.emit('send message', $messageBox.val());
$messageBox.val('');
});
socket.on('new message', function (data) {
$chat.append(data + "<br/>");
});
});
</script>
</body>
</html>
I'm using IntelliJ IDEA, I have every module and library that I need installed.
It appears that you have no route for the jQuery file you specify with this:
<script src='jquery-3.2.1.js'></script>
A nodejs express server does not server ANY files by default so unless you have a general purpose route for your static files or a specific file for that jQuery file, your express server will not know how to serve that file when the browser requests it.
You have several possible choices for how to fix that:
Change the jQuery URL in the script tag in your web page to point to one of the public CDNs for jQuery. There are often performance advantages to doing this. For example, you could change to this: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>.
Use express.static() on your server to configure a directory of static assets that will be automatically served by express when requested by the browser.
Create a specific route for the jQuery file just like you did with your exist app.get('/', ...)that responds to the/` GET request.
I have two clients which can interchange some data over socket.io. I also have a server. What i need to do is i want to send data from client 1 to client 2 over a socket and i am unable to figure out that how i can achieve it.Please note that client 1 and client 2 are different html pages.
Server.JS
var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
var ip=process.env.IP||"192.168.1.5";
app.use(express.static(__dirname));
server.listen(port,ip, function () {
console.log('Server listening at port %d ', port);
});
app.get('/index', function(req, res) {
res.sendFile(path.join(__dirname,'/test.html'));
})
app.get('/index1', function(req, res) {
res.sendFile(path.join(__dirname,'/test1.html'));
})
io.on('connection', function (socket) {
socket.on('broadcast', function (message) {
console.log(message);
socket.broadcast.emit('message', message);
});
console.log("connected");
});
Client1.JS
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script >
var socket = io.connect();
socket.emit('broadcast',"Broadcasting Message");
socket.on('message', function (data) {
alert(data)
});
</script>
</body>
Client2.JS
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script >
var socket = io.connect();
socket.on('message', function (data) {
alert(data)
//socket.emit('message',"Hello world");
});
</script>
</body>
Ok, here is what I did on my local and you may change it by your needs.
server.js
var io = require('socket.io')(80);
io.on('connection', function (socket) {
socket.on('broadcast', function (message) {
console.log(message);
socket.broadcast.emit('message', message);
});
console.log("connected");
});
client1.js
var socket = io.connect('ws://127.0.0.1');
socket.emit('broadcast',"Broadcasting Message");
socket.on('message', function (data) {
$('#client1').html(data);
});
client2.js
var socket = io.connect('ws://127.0.0.1');
socket.on('message', function (data) {
$('#client2').html(data);
});
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src='https://code.jquery.com/jquery-1.12.4.min.js'></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="client1.js"></script>
<script type="text/javascript" src="client2.js"></script>
</head>
<body>
<div> <h1> CLIENT 1 </h1><div id="client1"></div></div>
<div> <h1> CLIENT 2 </h1><div id="client2"></div></div>
</body>
</html>
On a termminal after you run, node server.js and reload your page, you will see client2 will have Broadcasting message html appended
Make sure to pass the URL to the server when instantiating WS on the client side... for example var socket = io.connect('http://localhost');
On the server side, each WS connection with each client is a unique instance. That is to say that for this purpose you must be deliberate about which WS connection you target when emitting events.
The first thing to solve is how to associate WS connection instances with specific clients. The answer to this is to use a map/dictionary/plain ol' javascript object with some sort of unique client identifier as the key and the instance of the WS connection as the value. Pseudo-code:
let connections = { 'client1': WSinstance, 'client2': WSinstance };
You would add to this object every time you create a new WS instance. Assuming you have a way to uniquely identify a client and that is stored in the variable clientId, you could do the following:
io.on('connection', function (socket) {
connections[clientId] = socket;
}
Now if you want to emit a message to just client1 you can use the WS instance associated with them by grabbing it from the object connections.client1 or if you want to target client2 connections.client2
hey guys m using to files for server side server.js and at client side using javascript
server.js
var express = require("express");
var io = require("socket.io").listen(app);
var app = express.createServer("localhost");
app.listen(3000);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/hello.html');
});
console.log("before");
io.sockets.on("connection", function (socket) {
console.log("after");
socket.on("message send", function (data) {
io.sockets.emit("new mesage", data);
});
});
and at client side using one html page name
hello.html
<html>
<head>
<style>
#chat{
height : 500px;
}
</style>
</head>
<body>
<div id="chat" > </div>
<form id ="send message">
<input id="message" type="text" ></input>
<input type="submit"></input>
</form>
<script type= "javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
var socket =io.connect();
var $messageForm = $("#send message");
var $messageBox=$("#message");
var $chat = $("#chat");
$messageForm.submit(function(e){
e.preventDefault();
socket.emit("message send" , $messageBox.val());
});
socket.on("new message", function(data){
$chat.append(data + "</br>");
});
});
</script>
</body>
</html>
when m start server then its proporly working but when i sent a request then it shows error like given blow
Failed to load resource: the server responded with a status of 404 (Not Found) /socket.io/socket.io.js
Uncaught ReferenceError: jQuery is not defined
versions
socket.io:0.9.16
exparess:3.4.0
thanks for your time :)
You need to bind the socket.io to the http server not the application server. Changes this to below..
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server);
Refer Express guide for more info.
EDIT
To correct the Jquery error..
replace
jQuery(function($){
with
$(document).ready(function($)