i am trying to integarte pubnub(replacing socket.io withh pubnub).here below i have shown code.it is working fine for pc.but in mobile devices its not working .i am not getting error as well.any body can tel what i done wrong.
till now i have tried to replace socket with my pubnub connection
import PubNub from 'pubnub';
import { PubNubProvider, usePubNub } from 'pubnub-react';
const pubnub = new PubNub({
publishKey: 'xxxxxxxxxxxx',
subscribeKey: 'xxxxxxxxxxx'
});
//leave Table when close window
const closingCode = () => {
sendMsg("leaveTable");
return null;
};
class App extends Component {
constructor(props) {
super(props);
this.state = {
isOpen: false
};
this.receiveMsg = []
}
window.onbeforeunload = closingCode;
// Read res from service via Socket IO
// socket.on("message", receiveMsg);
socket.on("message", text => {
let params = text.split("|"); //.map(p => Base64.Decode(p)); // we are not using b64 now
let message = params.shift(); // message, eg. playerSitOut, clearTable
this.receiveMsg.push(message);
this.props.updateMessage({ message, params });
});
pubnub.addListener({ message: function (m) {
const channelName = m.channel; // Channel on which the message was published
const channelGroup = m.subscription; // Channel group or wildcard subscription match (if exists)
const pubTT = m.timetoken; // Publish timetoken
const msg = m.message; // Message payload
const publisher = m.publisher; // Message publisher/ } });
//pubnub.subscribe();
}
Related
I have the following code that subscribes to a socket. I have noticed that under high frequency of messages, the display_data state sometimes falls out of sync. This occurs despite the client receiving all the messages in sequential order. Could this happen because React is setting the state in an asynchronous and mutable way? Are multiple messages being processed at the same time?
Would a better model for processing data to put the incoming messages into a client side queue and then process each item in the queue sequentially, removing item after processing, and then update the state? If this is ideal, how can I do this?
const client = new w3cwebsocket('ws://localhost:5424');
export class DataManager extends React.Component {
constructor(props) {
super(props);
this.state = {
display_data: {},
key_count: 0,
pipe_count: 0,
data_schema: data_schema
};
client.onopen = () => {
console.log('WebSocket connected!');
};
}
componentDidMount() {
client.onmessage = (message) => {
this.processIncomingMessage(message.data);
}
}
processIncomingMessage(message) {
let message_json = JSON.parse(message);
let message_type = message_json['type'];
let message_time = message_json['update_time'];
let message_data = message_json['data'];
let total_keys = message_json['total_keys'];
if (message_type === 'sync') {
this.setState({
display_data: message_json['data'],
});
} else {
let data = Object.assign({}, this.state.display_data);
Object.keys(message_data).forEach(index => {
data[message_data[index]['key']] = 1;
});
this.setState({
display_data: data,
});
console.log(message_json['pipe_count'], Object.keys(data).length, total_keys);
}
this.setState({
pipe_count: this.state.pipe_count + 1,
key_count: Object.keys(this.state.display_data).length
});
}
componentWillUnmount() {
client.close();
}
}
My React code creates a WebSocket connection to our company's ActiveMQ 5.15.5 server, and then subscribes to the following two topics: salary and decoding. The problem is that the code is only able to subscribe to one of the topics. It cannot subscribe to both.
const client = window.Stomp.client(`ws://${ipAddress}:61614`, 'aj6.stomp');
const headers = { id: 'username' };
client.debug = null;
client.connect('user', 'pass', () => {
client.subscribe(
'/topic/salary', //BREAKPOINT was set here
message => {
const body = JSON.parse(message.body);
if (body && body.pcId) {
salaries[body.pcId] = body;
setState({ salaries});
}
},
headers,
);
client.subscribe(
'/topic/decoding', //BREAKPOINT was set here
message => {
const newBody = JSON.parse(message.body);
if (newBody && newBody.PcID) {
consoleMessage[newBody.PcID] = newBody;
setState({ consoleMessage });
}
},
headers,
);
});
So in the code above I put a break-point at client.subscribe('/topic/decoding... and client.subscribe('/topic/salary.... I saw that it only subscribes to /topic/decoding but not /topic/salary.
Does anyone know how I can fix this issue so that it subscribes to both topics?
From Stomp documentation:
Since a single connection can have multiple open subscriptions with a server, an id header MUST be included in the frame to uniquely identify the subscription. The id header allows the client and server to relate subsequent MESSAGE or UNSUBSCRIBE frames to the original subscription.
Within the same connection, different subscriptions MUST use different subscription identifiers.
Stomp API definition:
subscribe(destination, callback, headers = {})
So for my understanding, You can't have the same username id for both of your subscriptions
Try creating 2 clients, e.g.:
const salaryClient = window.Stomp.client(`ws://${ipAddress}:61614`, 'aj6.stomp');
const salaryHeaders = { id: 'salary' };
salaryClient.debug = null;
salaryClient.connect('user', 'pass', () => {
salaryClient.subscribe(
'/topic/salary',
message => {
const body = JSON.parse(message.body);
if (body && body.pcId) {
salaries[body.pcId] = body;
setState({ salaries});
}
},
salaryHeaders,
);
});
const decodingClient = window.Stomp.client(`ws://${ipAddress}:61614`, 'aj7.stomp');
const decodingHeaders = { id: 'decoding' };
decodingClient.debug = null;
decodingClient.connect('user', 'pass', () => {
decodingClient.subscribe(
'/topic/decoding',
message => {
const newBody = JSON.parse(message.body);
if (newBody && newBody.PcID) {
consoleMessage[newBody.PcID] = newBody;
setState({ consoleMessage });
}
},
decodingHeaders,
);
});
I am getting error as "Must use destructuring state assignment" in react
I have routed this code in "Home.jsx"
My code is "MainPage.jsx". In this code I am sending userdetails to server and from server I am fetching hashcode value along with userdetails.
MainPage.jsx:
import React, { Component } from 'react';
export class MainPage extends Component {
constructor(props) {
super(props);
this.state = {
userCredientials: {
type: 'credentials',
name: 'vinay',
email: 'vinay3245#gmail.com',
},
mess: '',
userHashCode: '',
};
}
componentDidMount() {
this.connect();
}
/**
* #function connect
* This function establishes the connect with the websocket and also ensures constant
reconnection if connection closes
*/
connect = () => {
const ws = new WebSocket('ws://127.0.0.1:5678/');
// websocket onopen event listener
ws.onopen = () => {
console.log('connected websocket main component');
console.log(this.state);
ws.send(JSON.stringify(this.state.userCredientials)); //line no 32 -- error -- todo
};
// websocket onclose event listener
ws.onclose = () => {
console.log('closed');
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
this.setState({ userHashCode: data.hashCodeOfUser });
if (this.state.userHashCode) { //line no 43 -- error -- todo
this.setState({
mess: `Name: ${data.name} date: ${data.date} HashCode: ${data.hashCodeOfUser} Message: ${data.msg}`,
});
} else {
this.setState({
mess: `Name: ${data.name} Message: ${data.msg}`,
});
}
};
// websocket onerror event listener
ws.onerror = (err) => {
console.error('Socket encountered error: ', err.message, 'Closing socket');
ws.close();
};
};
/**
* utilited by the #function connect to check if the connection is close, if so attempts to
reconnect
*/
check = () => {
const { ws } = this.state;
if (!ws || ws.readyState === WebSocket.CLOSED) this.connect(); // check if websocket
instance is closed, if so call `connect` function.
};
render() {
return (
<div>
<p>{this.state.mess}</p> //line no 72 -- error -- todo
</div>
);
}
}
export default MainPage;
to see error in browser click this link
I have mentioned error in code as "todo"
If any one know please let me know the correct code.
The error means that you can not read this.state.attribute, and must read const { attribute } = this.state instead.
For example, on line 32:
const { userCredientials } = this.state;
ws.send(JSON.stringify(userCredientials));
The error is not a Javascript error per se, but an opinionated one. Javascript can and will compile, but somewhere along your build line that error is triggered. The most common place to write rules like that is in an eslint configuration file.
Running into an issue with React/Socket.io. I have two different socket emitters/listeners: one for a chat, and one for keeping track live changes to the application. I have two separate windows running localhost. The issue is when i emit a change on one window, the other window can receive that change the first time but never again (i.e. get first chat message but none that follow). After that first emit/receive, the sending client starts to receive its own emitters.
front end code:
`
socket = io("localhost:3002");
componentDidMount() {
//get id from url
const { id } = this.props.match.params;
//join specific room for project
this.socket.on("connect", () => {
this.socket.emit("room", this.projectId);
});
//listener for incoming messages
this.socket.on("RECEIVE_MESSAGE", (data) => {
this.props.addChat(this.projectId, data);
});
this.socket.on("UPDATE_PROJECT", () => {
console.log("update");
this.props.fetchProject(id);
});
}
emitTaskChange = () => {
this.socket.emit("TASK_CHANGE", { data: null });
};
onChatSubmit = (e) => {
e.preventDefault();
//create object with current user as author, message, and a timestamp
const chat = {
author: this.props.currentUser.name,
message: this.state.newChat,
createdAt: new Date().toLocaleString(),
};
//send message through socket
this.socket.emit("SEND_MESSAGE", chat);
//call action creator to add new chat
this.props.addChat(this.projectId, chat);
this.setState({ currentMessage: "" });
};
handleTaskEdit = (taskId, currentStatus) => {
const newStatus = currentStatus === "todo" ? "inprogress" : "completed";
this.props.editTask(this.projectId, taskId, newStatus);
this.emitTaskChange();
};
`
backend code:
`
const io = socket(server);
//create separate chat rooms using project id
io.on("connection", (socket) => {
socket.on("room", (room) => {
socket.join(room);
socket.in(room).on("SEND_MESSAGE", (message) => {
socket.emit("RECEIVE_MESSAGE", message);
});
socket.in(room).on("TASK_CHANGE", (data) => {
socket.emit("UPDATE_PROJECT", data);
});
});
`
found the error:
had to change the server-side code from socket.on and instead use the io object that was initialized such as io.sockets.on
I am facing issue in adding chat message in my Flatlist because I am not able to call any function inside stompClient.subscribe ()
My code is as following :
dummy='dummyurl';
sock = new SockJS(this.dummy);
componentDidMount() {
var that = this;
this.sock.onConnect =(e) =>{
console.log("connected")
}
this.sock.onopen = function() {
console.log('open');
var dummy2='dummyurl';
var sock2 = new SockJS(dummy2);
let stompClient = Stomp.over(sock2);
stompClient.heartbeat.outgoing = 20000;
stompClient.heartbeat.incoming = 0;
stompClient.connect({}, (frame) => {
stompClient.subscribe('xyz/getChat', (messageOutput) =>{
var mymessage =JSON.parse(messageOutput.body).message;
this.state = {
incomingchatMessage: "",
chatMessages:[]
}
that.setState({incomingchatMessage:mymessage}) //getting issue setState not found
console.log(this.state)
});
});
};
this.sock.onmessage =(e) =>{
console.log('message', e);
alert("on message calledj")
};
this.sock.onmessage = evt => {
console.log("erve");
}
}
In this code I am able to get net message inside new_message variable but not able to update state value here .
Any solution of this condition .