How to use socket io to update a chart at Next js real time connecting with java 11 spring boot? - socket.io

I am developing an application in java 11 spring boot and data base MySQL. Front-end I am using Next J's.
I need to learn how to use socket io to update a chart at Next js connecting with my back-end spring boot and update the chart in real time. If anyone can provide an example with the code to be used I will be very grateful! Thanks in advance.
I didn't find anything really helpful to use in my code.
here the code back-end java: https://github.com/gomes007/files
and here the front-end:
import React from 'react'
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
const Home = () => {
const socket = new SockJS('http://localhost:8080/ws');
console.log(socket);
const stompClient = Stomp.over(socket);
stompClient.connect({}, (frame) => {
stompClient.subscribe('/topic/messages',
(message) => {
console.log(message.body);
});
stompClient.send("/app/message", {}, JSON.stringify({message: 'Hello World!'}));
});
return (
<div>
</div>
)
}
export default Home

Related

Can't emit from server to client and from client to server [Socket.io]

I'm creating my product and stuck with this problem. One day I setuped socket.io and everything worked well. On the next day I migrate my server and client from http to https. After the migration client side and server side still connected, but I can't emit from client side to server and from server to client.
Server side
I have my ssl certificate inside ./security/cert.key and ./security/cert.pem they are loading correctly. My server running on https://localhost:5000
import fs from "fs";
import https from "https";
import socketio from "socket.io";
import express from "express";
// HTTPS optiosn
const httpsOptions = {
key: fs.readFileSync("./security/cert.key"),
cert: fs.readFileSync("./security/cert.pem"),
};
// Setup express and https server
const app = express();
const server = https.createServer(httpsOptions, app);
// Setup socket io
const io = socketio.listen(server, {
origins: "https://localhost:3000",
transports: ["websocket"],
});
server.listen(5000, () => {
console.log(`server listening on https://localhost:5000`);
});
io.listen(server);
io.on("connection", (socket) => {
console.log("new socket connected!");
console.log(`data = ${socket.handshake.query.data}`);
socket.emit("some-event");
socket.on("some-event-2", () => console.log("some-event-2 happened!"));
});
Client Side
My example react component. My react app is running on https://localhost:3000. HTTPS is connected and working well.
import React from "react";
import io from "socket.io-client";
const Sandbox: React.FC = () => {
const query = {
"data": 123,
};
const socket = io.connect("https://localhost:5000", {
secure: true,
query,
transports: ["websocket"],
});
socket.on("connect", () => console.log("connect!"));
socket.on("some-event", () => console.log("some event happened"));
socket.emit("some-event-2");
return <React.Fragment />;
};
export default Sandbox;
And now the problem. On client side in console I should see connect! and some event happened
And on server side I should see the messages new socket connected! and data = 123, some-event-2 happened!. But instead my client side console is completely clear
And server side console have only a few logs, but dont contains emit logs
What should I do? Maybe I'm incorrectly using socket.io with https?
I fixed my error.
The problem was that I was firstly create https server and after that only call .listen() on it. listen() - is not a void, it's return another server obj. You need to pass the result of .listen() function inside your io.listen()
// Don't do that❌
var server = https.createServer(options, app);
server.listen(5000);
io.listen(server);
// Do that✅
var server = https.createServer(options, app).listen(5000);
io.listen(server);

Whoops! Lost connection to http://198.x.x.x:hostnumber/websocket

I am using SocksJs and getting every time Whoops! Lost connection to Http or if I changed the link to ws://198.x.x.x:hostnumber/websocket then i will get
'SyntaxError: The URL's scheme must be either 'http:' or 'https:'. 'ws:' is not allowed.
SyntaxError: The URL's scheme must be either 'http:' or 'https:'. 'ws:' is not allowed.'
also, I am sharing my code
import * as Stomp from 'stompjs';
import * as SockJS from 'sockjs-client';
connectNew() {
const socket = new SockJS(this.serverUrl);
this.stompClient = Stomp.over(socket);
this.stompClient.connect('', '', () => {
console.log('success');
});
}
Please help if anybody knows the answer I want to run this code on my mobile phone

STOMPJS over and subscribe methods not working with Spring, SockJs, npm, webpack

I want to use websocket with SockJs and Stomp client-side, and Java server-side, in a Spring-boot web application. I have installed with npm sockjs-client and stompjs. My client-side code is:
var SockJS = require('sockjs-client');
var Stomp = require("stompjs");
var socket = new SockJS('/webSocketEndPoint');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
stompClient.subscribe('/topic/notification', function (notificationBody) {
alert(JSON.parse(notificationBody.body).content);
});
})
The methods over and subscribe are not working, so the websocket i want to build is not working. IntelliJ say me "Unresolved function or method over" and "Unresolved function or method subscribe ". I've included in my package.json stompjs and sockjs-client (correct version). The initial requires not makes me problem, but i'm not able to run this script..Someone can help me?! Thanks a lot
Maybe because of wrong quotes in require("stompjs")?
Here is my workin example:
let SockJS = require('sockjs-client');
const Stomp = require('stompjs');
function register(registrations) {
let socket = SockJS('/webSocketEndPoint');
let stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
registrations.forEach(function (registration) {
stompClient.subscribe('/topic/notification', function (notificationBody) {
alert(JSON.parse(notificationBody.body).content);
});
});
});
}

Socket.io not working with React Native on Android

I'm learning React Native recently, and having trouble with using Socket.IO. I'm using latest React native and cli(just updated), and this is my code:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
window.navigator.userAgent = 'react-native';
const io = require('socket.io-client/socket.io');
const socket = io('localhost:3000', { jsonp: false });
socket.connect();
class wschat extends Component { ... }
You can see, the code is quite simple, and no error. This is my server code:
"use strict";
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
http.listen(3000, () => {
console.log('WSChat Server for React-Native listening on port 3000');
});
io.on('connection', (socket) => {
console.log('connected: ' + socket.id);
});
Seems fine, and it is actually worked with ios, but not worked on android. I was enabled remote debugger, and checked the properties, and Socket.IO it self it was loaded well, but no connection was established. You can see the server code, when 'connection' event occured, logged on console.
I used AVD(nexus5) and my device(LG G4 optimus), but both won't worked. What am I missing? Any advice will be very appreciate it!
The VM react-native runs in isn't nodejs. This means you can't rely on packages such as socket.io-client that in turn rely on nodejs native modules (http, fs, crypto, etc)
I.e. socket.io-client relies on engine-i.o and there you will find stuff like:
var http = require('http');
What's devious is that as long as you're in dev-mode, iOS is backed by nodejs, so it may look like all is working, but if you compile the app, it won't.
Check out react-native-socketio, sadly (as of 2016-09-12) the project isn't well maintained, but it can be made to work.
If you want to use socket io for your react native project I would suggest you use feathers js socket io.
https://docs.feathersjs.com/api/socketio.html
This framework also supports Primus, Express, and REST so you got lots of options to choose from. Hope this will help.

React Native with socket.io doesn't work

i create simple socket.io server and react native project and tested, but socket.io on React Native doesn't work at all.
i printed "socket.io-client" on console and it's loaded well, and i made simple HTML file with using socket.io, it works, but only React Native doesn't work.
i'm using React native 0.26.2, and socket.io 1.4.6.
this is my server code:
"strict mode";
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
io.on('connection', (socket) => {
console.log('user connected');
});
http.listen(3000, () => {
console.log('server started on 3000');
});
// web testing
app.get('/', (req, res, next) => {
res.sendFile(__dirname + '/index.html');
});
and this is rn code:
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, TextInput, TouchableHighlight, View } from 'react-native';
import "./userAgent"; //window.navigator.userAgent = "react-native";
const io = require('socket.io-client/socket.io');
class SocketChat extends Component {
constructor(props) {
super(props);
this.socket = io('localhost:3000', { jsonp: false });
this.state = {
text: null
};
}
...
}
as i heard, using React native with socket.io causes ajax long polling instead of websocket, so i added 'user-agent' trick. whether it is working or not, even connection isn't established, but if i try with browser, it works well. it will be very appreciate me that tell me what should i do.
I solved this by replacing another websocket module. Socket.IO doesn't work on Android and as someone said to me, Socket.io uses node native modules internally so it should be not working after build production app.

Resources