SocketIO 4 - won't emit to the room - socket.io

I have following server code:
const path = require("path");
const http = require("http");
const express = require("express");
const {instrument} = require('#socket.io/admin-ui')
const {jwtDecode, jwtVerify, resignJwt} = require('jwt-js-decode')
const secret =
"xxxxxxx";
const app = express()
const server = http.createServer(app)
const io = require("socket.io")(server, {
cors: {
origin: ["https://admin.socket.io", "http://localhost:3001"],
credentials: true
},
});
let servantID = ''
io.use((socket, next) => {
const header = socket.handshake.headers["authorization"];
jwtVerify(header, secret).then((res) => {
if (res === true)
{
const jwt = jwtDecode(header);
servantID = jwt.payload.iss;
return next()
}
return next(new Error("authentication error"));
});
});
instrument(io, { auth: false });
server.listen(3000, () =>
console.log('connected')
)
io.on('connection', socket => {
socket.on("join", (room, cb) => {
console.log('Joined ' + room);
socket.join(room);
cb(`Joined the best room ${room}`)
});
socket.on('newOrder', function (data) {
socket.to('servant').emit('this', data);
console.log(data);
})
socket.on("thisNew", function (data) {
console.log('this new');
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
})
And client side code:
socket.emit('join', 'servant', message => {
console.log(message)
})
socket.on('this', () => {
console.log('this event')
})
socket.emit('newOrder', 'data')
When I emit like this:
socket.to('servant').emit('this', data);
the client doesn't receive anything, but if I emit without room:
socket.emit('this', data);
the event and data are received on the client side.
What am I doing wrong here?

Related

socket.io client 's namespace invalid

I am running on the latest version of socket.io, the server code and client code below works well.
// server
const { Server } = require("socket.io"),
http = require('http');
const httpserver = http.createServer();
io.on("connection", async (socket) => {
socket.on("error", (err) => {
console.log(err.message);
});
socket.on('disconnect', function () {
console.log('socket disconnect');
})
});
const io = new Server(httpserver, {
cors: { origin: "*", methods: ["GET", "POST"],}
});
httpserver.listen(3001, () => {
console.log('listening on *:3001');
});
// client
import { io, Socket } from "socket.io-client";
const socket = io('ws://127.0.0.1:3001', {
transports: ["websocket"]
});
socket.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
then I tried to work with namespace in socket.io
// server
io.of("device").on("connection", async (socket) => {
socket.on("error", (err) => {
console.log(err.message);
});
socket.on('disconnect', function () {
console.log('socket disconnect');
})
});
// client
const socket = io('ws://127.0.0.1:3001/device', {
transports: ["websocket"]
});
running the code gives me an error saying
'connect_error due to Invalid namespace''
I can't figure out what goes wrong
Using ws://127.0.0.1:3001/device means you are trying to reach the namespace named '/advice', which does not exist on the server.
I think you are looking for the path option instead:
const socket = io("ws://127.0.0.1:3001", {
path: "/device",
transports: ["websocket"]
});
References:
https://socket.io/docs/v4/client-initialization/
https://socket.io/docs/v4/client-options/#path
https://socket.io/docs/v4/namespaces/

Not getting Apollo Client subscription data

I'm trying to get subscription data. The server gives the data if you look through the Explorer.
Client:
const httpLink = createHttpLink({
uri
});
const wsLink =
typeof window !== "undefined"
? new GraphQLWsLink(
createClient({
url,
on: {
connected: () => console.log("Connected client!"),
closed: () => console.log("Closed ws-connection!"),
},
})
)
: null;
const splitLink =
typeof window !== "undefined" && wsLink != null
? split(
({ query }) => {
const def = getMainDefinition(query);
return (
def.kind === "OperationDefinition" &&
def.operation === "subscription"
);
},
wsLink,
httpLink
)
: httpLink;
const authLink = setContext((_, { headers }) => {
const {token} = useTokenFromCookie();
return {
headers: {
...headers,
authorization: token ? `Bearer ${token()}` : "",
}
}
});
const client = new ApolloClient({
link: authLink.concat(splitLink),
cache: new InMemoryCache({addTypename: false}),
defaultOptions: {
mutate: { errorPolicy: 'all' },
},
});
gql:
subscription ReadRegisterData($equipmentId: Int!, $addressRegistry: Int!) {
readRegisterData(equipment_id: $equipmentId, address_registry: $addressRegistry) {
equipment_id
address_registry
type_of
data_from_controller
}
}
Hook:
const useSubscriptionReadRegisterData = (equipment_ip:number, address_registry: number) => {
const { data, error, loading} = useSubscription(READ_REGISTER_DATA, {
variables: {
equipmentIp: equipment_ip,
addressRegistry: address_registry
}
});
console.log("data", data)
const dataRegisterSubscription = (data) ? data.readRegisterData : null;
return { dataRegisterSubscription, error, loading }
}
export default useSubscriptionReadRegisterData;
In the console writes:
The connection is established, then immediately the connection is closed
WS connection status 101
When you start listening to a subscription through Explorer, on the server, when outputting data to the log, you can see that there is 1 Listener. When you run in the application, it does not show any Listener

How to implement an optimistic update when using reduxjs/toolkit

My reducer file is below
const slice = createSlice({
name: "hotels",
initialState: {
list: [],
loading: false,
lastFetch: null,
},
reducers: {
hotelsRequested: (hotels) => {
hotels.loading = true;
},
hotelsRequestFailed: (hotels) => {
hotels.loading = false;
},
hotelsReceived: (hotels, action) => {
hotels.list = action.payload;
hotels.loading = false;
hotels.lastFetch = Date.now();
},
hotelEnabled: (hotels, action) => {
const { slug } = action.payload;
const index = hotels.list.findIndex((hotel) => hotel.slug === slug);
hotels.list[index].active = true;
},
},
});
export const {
hotelsReceived,
hotelsRequestFailed,
hotelsRequested,
hotelEnabled,
} = slice.actions;
export default slice.reducer;
//Action creators
export const loadHotels = () => (dispatch, getState) => {
const { lastFetch } = getState().entities.hotels;
const diffInMinutes = moment().diff(lastFetch, "minutes");
if (diffInMinutes < 10) return;
dispatch(
hotelApiCallBegan({
url: hotelUrl,
onStart: hotelsRequested.type,
onSuccess: hotelsReceived.type,
onError: hotelsRequestFailed.type,
})
);
};
export const enableHotel = (slug) =>
hotelApiCallBegan(
{
url: `${hotelUrl}${slug}/partial-update/`,
method: "put",
data: { active: true },
onSuccess: hotelEnabled.type,
},
console.log(slug)
);
My api request middleware function is as follows
export const hotelsApi = ({ dispatch }) => (next) => async (action) => {
if (action.type !== actions.hotelApiCallBegan.type) return next(action);
const {
onStart,
onSuccess,
onError,
url,
method,
data,
redirect,
} = action.payload;
if (onStart) dispatch({ type: onStart });
next(action);
try {
const response = await axiosInstance.request({
baseURL,
url,
method,
data,
redirect,
});
//General
dispatch(actions.hotelApiCallSuccess(response.data));
//Specific
if (onSuccess) dispatch({ type: onSuccess, payload: response.data });
} catch (error) {
//general error
dispatch(actions.hotelApiCallFailed(error.message));
console.log(error.message);
//Specific error
if (onError) dispatch({ type: onError, payload: error.message });
console.log(error.message);
}
};
Could anyone point me in the right direction of how to add an optimistic update reducer to this code. Currently on hitting enable button on the UI there's a lag of maybe second before the UI is updated. Or maybe the question, is do i create another middleware function to handle optimistic updates? If yes how do i go about that? Thanks

Network Request failed while sending image to server with react native

i want to send image to a server and getting the result with a json format but the application returns a Network Request failed error
react native 0.6 using genymotion as emulator
i tried RNFetchblob but the result take a long time to get response (5 min )
also i tried axios but it response with empty data with 200 ok
this is the function that import the image
OnClick = () => {
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("Image Picker Error: ", response.error);
} else {
let source = { uri: response.uri };
// You can also display the image using data:
//let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source,
data: response.data,
BtnDisabled: false
});
console.log();
}
});
};
and this method that sends the image
Send = async () => {
let url = "http://web001.XXX.com:8000/api/prediction/check_prediction/";
let UplodedFile = new FormData();
UplodedFile.append('file',{ type:'image/jpeg', uri : this.state.avatarSource , name:'file.jpeg'});
fetch(url, {
method: 'POST',
body:UplodedFile
})
.then(response => response.json())
.then(response => {
console.log("success");
console.log(response);
})
.catch(error => {
console.error(error);
});
i expect json format
ScreenShot here
can you change your code like this?
OnClick = () => {
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("Image Picker Error: ", response.error);
} else {
let source = { uri: response.uri };
// You can also display the image using data:
//let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
pickerResponse: response,
data: response.data,
BtnDisabled: false
});
console.log();
}
});
};
Send = async () => {
let url = "http://web001.XXX.com:8000/api/prediction/check_prediction/";
let UplodedFile = new FormData();
UplodedFile.append('file',{ type:'image/jpeg', uri : this.state.pickerResponse.path , name:'file.jpeg'});
axios({
method: "post",
url: url,
data: UplodedFile
})
.then(response => {
console.log("success");
console.log(response);
})
.catch(error => {
console.error(error);
});

node.js - Socket IO times out after some time

I'm trying to build up a socket.io server for my own multiplayer game, but for some reason the server goes down after a certain amount of time and I don't know why. I have tried several ways to run the server (nodemon and forever, everything with or without screen). I don't think that this is an inactivity problem because I added a random stuff generator to simulate some activity on the server, yet the problem persists. My cpu load with the running server stays between 2-3 %. I'm running node 4.x and the current stable socket.io build (1.3.6).
And here is my code:
var shortId = require('shortid'),
io = require('socket.io')(process.env.PORT || 4567),
mysql = require('mysql'),
connection = mysql.createConnection({
host: 'localhost',
user: 'xxx',
password: 'xxx',
database: 'xxx'
});
var clients = [];
var clientLookup = {};
//Placed Components (builded stuff from players or enviroment)
var placed_components = 'Server1_PlacedC';
connection.connect(function (err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
});
setInterval(function () {
var random = Math.random();
//connection.query(
// 'INSERT INTO '+placed_components+' SET ?',
// {data:countdown},
// function(err,result){
// if (err) throw err;
// }
//);
console.log(random);
}, 100);
io.on('connection', function (socket) {
var currentClient;
console.log('connected', socket.id);
//////////////////////////////////////////////////////////////////////////////
socket.on('disconnect', function () {
console.log('player disconnected', currentClient.id);
socket.broadcast.emit('disconnected', currentClient)
var index = clientLookup[currentClient.id];
clients.splice(index, 1);
})
///////////////////////////////////////////////////////////////////////////// /
socket.on('register', function (data) {
currentClient = {
id: shortId.generate(),
health: 100,
isDead: false
};
console.log('registering', currentClient.id);
clients.push(currentClient);
clientLookup[currentClient.id] = currentClient;
socket.emit('registerSuccess', {id: currentClient.id});
socket.broadcast.emit('spawn', {id: currentClient.id});
console.log('connected players', clients.length);
clients.forEach(function (client) {
if (currentClient.id == client.id)
return;
socket.emit('spawn', {id: client.id});
console.log('sending spawn to new player for playerid', client.id);
})
});
socket.on('beep', function () { // Beep Request
socket.emit('boop');
console.log("received some beep!");
});
socket.on('move', function (data) {
data.id = currentClient.id;
socket.broadcast.emit('move', data);
//console.log(JSON.stringify(data));
});
socket.on('ShareObject', function (data) {
data.id = currentClient.id;
socket.broadcast.emit('ReveiveObject', data);
console.log(JSON.stringify(data));
});
socket.on('SharePlayerAnimation', function (data) {
data.id = currentClient.id;
socket.broadcast.emit('BroadcastPlayerAnimation', data);
console.log("a Player changed his animation" + JSON.stringify(data));
});
//////////////////////////////////////////////////////////////////////////////
socket.on('benchmark', function (data) {
console.log(data);
});
//////////////////////////////////////////////////////////////////////////////
})
console.log('server started');

Resources