I start create server with Nodejs and socket.io in simple way.
In client connect just fine but when emit pong to server it never show.
This code:
SERVER
var PORT = 3003;
var io = require('socket.io')(PORT);
var clients = [];
setInterval (function() {
io.sockets.emit('ping');
}, 3000);
io.on('connection', (function(socket) {
socket.emit ('welcome', { message: 'Connection complete', id: socket.id });
clients.push ({id: socket.id, clientSocket: socket});
print ('Client connected ' + socket.id);
socket.on('disconnect', function() {
clients.splice(clients.indexOf(socket), 1);
print (socket.id + " is disconnected.");
});
socket.on('pong', function(args) {
print (args + " is pong.");
});
}).bind(this));
print('Server starting ...');
CLIENT:
var PORT = 3003;
var io = require('socket.io-client');
var socket = io.connect('http://localhost:' + PORT);
socket.on('connect', function(){
print ('Client connected...');
});
socket.on('welcome', function(args) {
print (args.message + ' / ' + args.id);
// socket.disconnect();
});
socket.on ('ping', function(args) {
socket.emit ('pong', { id: socket.id });
print ('Receive ping...');
});
print ('Client Starting...');
Related
I am loading my scripts using
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="/js/chat.js"></script>
My chat.js script is :
var socket = io();
socket.on('connect', function(){
var chatForm = document.forms.chatForm;
if (chatForm) {
var chatUsername = document.querySelector('#chat-username');
var chatMessage = document.querySelector('#chat-message');
chatForm.addEventListener("submit", function(e){
console.log("working")
//prevents page from reloading
e.preventDefault();
//emit the message with the socket
socket.emit('postMessage',{
username: chatUsername.value,
message: chatMessage.value,
});
chatMessage.value='';
chatMessage.focus();
});//chatform event
socket.on('updateMessages', function(data) {
showMessage(data);
});//update messages
}//chatForm
})
function showMessage(data) {
var chatDisplay = document.querySelector('.chat-display')
var newMessage = document.createElement('p');
newMessage.className = 'bg-success chat-text';
newMessage.innerHTML = '<strong>' + data.username + '<strong>:</strong>' +
data.message
chatDisplay.insertBefore(newMessage, chatDisplay.firstChild);
}
My app.js file uses:
app.set('port', process.env.PORT || 3000 );
var server = app.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
io.attach(server);
io.on('connection', function(socket) {
console.log("user connected");
socket.on('postMessage', function(data) {
io.emit('updateMessages', data);
});
});
I am getting the following errors in my console and have no idea how to fix them. Somebody please help!
The server is listening on port 3000. My console is saying that there is an unhandled 'error' event
In your app.js file, you should connect socketIO before listening:
const socketIO = require('socket-io');
const io = socketIO(app);
io.on('connection', function(socket) {
console.log("user connected");
socket.on('postMessage', function(data) {
io.emit('updateMessages', data);
});
});
app.set('port', process.env.PORT || 3000 );
app.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
Let try it, because I think after listening, everything won't work. We should connect socketIO before listening.
When no room is specified client receive the message but when specify a room I am unable to receive message on client.
server.js
var socket = require('socket.io');
var mysql = require('mysql');
const path = require('path');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen(server);
var port = PORT;
io.on('connection', (socket) => {
console.log('new connection made');
socket.on('subscribe', function (room) {
socket.room = room;
socket.join(socket.room, function () {
console.log('joined:' + room); // outputs joined: 1
socket.on('send-message', (data) => {
io.to(data.room).emit('message-received', data.message);
console.log("sent to room:" + data.room); // outputs sent to room: 1
});
});
});
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
client.js
this.socket = io.connect('ws://IP:PORT');
this.socket.on('connect', () => {
console.log("connection made"); // it output connection made in console
this.socket.emit('subscribe', 1);
});
this.socket.on('message-received', (message: any) => {
console.log(message);
});
on server.js I have tried several options below but still unable to emit 'message-received' on client side:
// io.emit('message-received', data);
// io.to(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
// io.sockets.in(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
//io.broadcast.to(data.room).emit('message-received', data.message);
using latest socket.io library with angular 4
based on what i see on your clientside and serverSide code, I believe the problem is in the clientSide code...
On your server, inside the 'subscribe' event the server is also listening for 'send-message' event, which you're never emiting from the client side!!
Therefore, if you emit 'send-message' event with data(this should include message) as parameter, only then the server would emit 'message-received' event to the client..
HOPE THIS HELPS!
I wanna create socket server like a Socket.io because socket.io can't work with Corona SDK. So I need custom socket server. I create socket server with using net module and it is work good. But I need using http module because I write REST API. I try create sample socket server from http module but have errors.
var net = require('net');
var HOST = 'localhost';
var PORT = 9999;
var server = require('http').createServer(function(request, response) {
response.end('Hello from server');
});
server.on('connection', function(socket) {
socket.on('data', function(data) {
data = data.toString('utf-8');
console.log(data);
socket.write('Hello from server');
});
socket.on('error', function(error) {
console.log(error);
});
});
server.listen(PORT, HOST);
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Chuck Norris!');
});
client.on('data', function(data) {
console.log('DATA: ' + data);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
If I run this script I got error:
CONNECTED TO: localhost:9999
I am Chuck Norris!
Error: This socket is closed
at Socket._writeGeneric (net.js:692:19)
at Socket._write (net.js:743:8)
at doWrite (_stream_writable.js:329:12)
at writeOrBuffer (_stream_writable.js:315:5)
at Socket.Writable.write (_stream_writable.js:241:11)
at Socket.write (net.js:670:40)
at Socket.<anonymous> (/var/work/projects/edorium/Server/test/test.js:49:16)
at emitOne (events.js:101:20)
at Socket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
{ Error: Parse Error
at socketOnData (_http_server.js:411:20)
at emitOne (events.js:101:20)
at Socket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
at Socket.Readable.push (_stream_readable.js:136:10)
at TCP.onread (net.js:560:20) bytesParsed: 0, code: 'HPE_INVALID_METHOD' }
Connection closed
Why this happed and how fix this?
Additional to answer
I add HTTP headers to request and all works good!
Code sample below:
var http = require('http');
var net = require('net');
var express = require('express');
var HOST = 'localhost';
var PORT = 9999;
var app = express();
var server = http.Server(app);
app.get('/', function (req, res) {
res.send('Hello World!fff');
});
server.listen(PORT, HOST);
server.on('connection', function(socket) {
socket.on('data', function(data) {
data = data.toString('utf-8');
console.log(data);
socket.write('Hello from server');
});
socket.on('error', function(error) {
console.log(error);
});
socket.on('end', function() {
console.log('Socket end');
});
});
// Client
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
var messagae = '' +
'GET /' +
'Host:localhost:9999' +
'Content-Type:text/plain;charset=windows-1251' +
'Content-Length:6' +
'Connection:Keep-Alive;' +
'Hello!';
client.write(messagae);
});
client.on('data', function(data) {
console.log('DATA: ' + data);
});
client.on('close', function() {
console.log('Connection closed');
});
at TCP.onread (net.js:560:20) bytesParsed: 0, code: 'HPE_INVALID_METHOD' }
Since you have explicitly created a HTTP server this server is expecting a HTTP request. But you are just sending "I am Chuck Norris!" which is definitely not a HTTP request. Therefore the server closes the connection.
To send a HTTP request you might use http.request. Alternatively you can study the HTTP standard and build a proper HTTP request yourself.
Your client was disconnect
var net = require('net');
var HOST = 'localhost';
var PORT = 9999;
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.on('data', function(data){
console.log(data);
textChunk = data.toString('utf8');
console.log(textChunk);
socket.write("================");
});
});
server.listen(PORT, '127.0.0.1');
server.listen(PORT, HOST);
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Chuck Norris!');
});
var i = 0;
client.on('data', function(data) {
console.log('Received: ' + data);
i++;
if(i==2)
client.destroy();
} );
client.on('close', function() {
console.log('Connection closed');
});
I have a simple app running on docker container. This container is not running all the time. It starts, does certain job and stops. When it is up, I would like to connect it to a server via socket.io. I have tried to use socket.io-client but still unable to make it works. This is my app code:
var docker_host_ip = process.env.DOCKER_HOST_IP;
var address = 'http://' + docker_host_ip +":" + port;
console.log("console : " + address);
var socket = require('socket.io-client')(address);
socket.on("disconnect", function(){
console.log("disconnected ");
});
socket.on("connect_failed", function(err){
console.log("err : " + err);
});
socket.on('connect', function(){
console.log("connected");
});
socket.on('news', function(data){
console.log("data : " + data);
socket.emit("news", {docker: "This is docker"});
});
socket.emit("news", {docker: "This is docker"});
socket.on('error', function (err) {
console.log(err);
});
I used this https://github.com/socketio/socket.io-client.
var port = 4000;
app.use(express.static('.'))
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
socket.emit("news", {"hello": "hello"});
socket.on("news", function(data){
console.log( "new " + data);
io.sockets.emit("news", data);
});
socket.on('disconnect', function() {
console.log('Got disconnect!');
});
});
app.get("/", function(res, req){
req.sendFile(path.join('/index.html'));
});
http.listen(port, function(){
console.log('listening on *' + port);
});
My app is not showing any error, but not message is sent. My server is working correctly through browser (with socket.io).
Can someone please tell me what is wrong ?
You have two same socket.emit message names, I guess the server send the message first.
server
socket.emit("news", {"hello": "hello"});
socket.on("news1", function(data){
console.log( "new " + data);
io.sockets.emit("news2", data);
});
client
socket.on('news', function(data){
console.log("data : " + data);
socket.emit("news1", {docker: "This is docker"});
});
socket.on('news2', function(data){
console.log("data : " + data);
});
Executing this code:
var fs = require('fs');
var Socket = require('net').Socket;
var socket = new Socket();
console.log('connecting to: ' + server.host + ':' + server.port );
socket.connect( server.host, server.port );
socket.on('error', function(err) {
console.log(arguments);
});
socket.on('connect', function() {
console.log('connected');
});
socket.on('end', function() {
console.log('socket ended');
});
Always throws this error:
{ '0': { [Error: connect ENOENT] code: 'ENOENT', errno: 'ENOENT', syscall: 'connect' } }
I'm on CloudLinux(x64) based shared hosting with SSH access.
You have your host and port backwards. According to the documentation, you should be doing:
socket.connect(server.port, server.host);
Server Side:-
var net = require('net');
var server = net.createServer(functi`on (socket){
socket.write("hi\n");
socket.write("you there\n");
socket.on("data", function(dd) {
console.log(data);
});
});
server.listen(8001);
Client side:-
var fs = require('fs');
var Sock = require('net');
var socket = Sock.Socket();
socket.connect(8001,"127.0.0.1", function() {
console.log('connecting to: ' + server.host + ':' + server.port );
});
socket.on('connect', function() {
console.log('connected');
});
socket.on('error', function(err) {
console.log(arguments);
});
socket.on('end', function() {
console.log('socket ended');
});