not connecting to spring websocket server - react-native

It is not connecting to the websocket server.I am using webstomp-client for react native.Plz, help me !
Here is my code,
componentWillMount() {
let msg = '';
const options = {
debug: true,
protocols: webstomp.VERSIONS.supportedProtocols()
}
this.stompClient = webstomp.client("ws://192.168.3.167:8080/test", options)
this.stompClient.connect({}, (frame) => {
console.log("OK")
this.stompClient.subscribe('/topic/greetings', (greeting) => {
msg = JSON.parse(greeting.body);
});
this.setState({
connected: true,
message: msg
})
}, (err) => console.log(err))
}
and logs...
Opening Web Socket...
webstomp.js:243 Web Socket Opened...
webstomp.js:243 >>> CONNECT
accept-version:1.2,1.1,1.0
heart-beat:10000,10000
Thanks in advance.

Got the same issue. Had to implement a custom WebSocketHandlerDecorator with:
public void handleMessage(final WebSocketSession session, final WebSocketMessage<?> message) throws Exception {
if (message instanceof TextMessage) {
TextMessage msg = (TextMessage) message;
String payload = msg.getPayload();
// only add \00 if not present (iOS / Android)
if (!payload.substring(payload.length() - 1).equals("\u0000")) {
super.handleMessage(session, new TextMessage(payload + "\u0000"));
return;
}
}
super.handleMessage(session, message);
}
Based on https://github.com/facebook/react-native/issues/12731

Related

amqplib not connecting to localhost RabbitMQ

I went through several SO threads regarding this. Didn't work anything. But my case is different. In my case, nothing happens. Here is the code:
import amqplib from 'amqplib'
const AMQP_URL = 'amqp://guest:guest#localhost:5672/'
const AMQP_QUEUE_NAME = 'email_queue'
function connectRabbitMQ() {
console.log('Connecting to rabbit mq...')
amqplib.connect(AMQP_URL, async (err: Error, connection: amqplib.Connection) => {
if (err) {
console.log('This log doesn\'t print')
throw err
}
console.log('This log doesn\'t print')
// Listener
const channel1 = await connection.createChannel()
channel1.consume(AMQP_QUEUE_NAME, (msg) => {
if (msg !== null) {
console.log('Recieved:', msg.content.toString());
channel1.ack(msg);
} else {
console.log('Consumer cancelled by server');
}
})
// Sender
const channel2 = await connection.createChannel()
setInterval(() => {
channel2.sendToQueue(AMQP_QUEUE_NAME, Buffer.from('something'))
}, 1000)
})
}
function launchServer() {
console.log('Launching Server...')
console.log('Connecting to MongoDB...')
const MONGODB_URI = process.env.MONGODB_URI?.toString() || ''
mongoose.connect(MONGODB_URI, {}, (err) => {
if (err) {
return console.error('Error connecting to Mongo DB !')
}
console.log('CONNECTED TO MONGO DB')
const port = parseInt(process.env.PORT?.toString() || '3000')
app.listen(port)
console.log('========= SERVER STARTED ========== PORT ' + port)
connectRabbitMQ()
})
}
launchServer()
Neither error nor success occur. The log doesn't get printed. Last log get printed is - Connecting to rabbit mq...
function connectRabbitMQ doesn't seems to be executed.
try appending this on last line of your code
connectRabbitMQ();

How to handle message sent from server to client with RSocket?

I try to use RSocketRequester to send a message from the server to the specific client, but I don't know how to handle it on the frontend. The server is Spring Webflux with the controller like this:
data class Message(val message: String)
#Controller
class RSocketController {
private val log = LoggerFactory.getLogger(RSocketController::class.java)
#MessageMapping("say.hello")
fun sayHello(message: String): Flux<Message> {
log.info("say hello {}", message)
return Flux.just(Message("server says hello"))
}
#MessageMapping("say.hi")
fun sayHi(message: String, rSocketRequester: RSocketRequester): Flux<Message> {
log.info("say hi {}", message)
rSocketRequester
.route("say.hello")
.data(Message("server says hi hello ;)"))
.send()
.subscribe()
return Flux.just(Message("server says hi!!"))
}
}
On the frontend I use rsocket-js. The sayHello method works just fine (request-stream), but when I call the sayHi method I want to send two messages from the server. The first one to say.hello endpoint, and the second to say.hi endpoint. I've got rsocket-js implementation like this:
sayHello() {
console.log("say hello");
this.requestStream("say.hello");
},
sayHi() {
console.log("say hi");
this.requestStream("say.hi");
},
connect() {
const transport = new RSocketWebSocketClient({
url: "ws://localhost:8080/rsocket"
});
const client = new RSocketClient({
serializers: {
data: JsonSerializer,
metadata: IdentitySerializer
},
setup: {
keepAlive: 60000,
lifetime: 180000,
dataMimeType: "application/json",
metadataMimeType: "message/x.rsocket.routing.v0"
},
transport
});
client.connect().subscribe({
onComplete: socket => {
this.socket = socket;
console.log("complete connection");
},
onError: error => {
console.log("got connection error");
console.error(error);
},
onSubscribe: cancel => {
console.log("subscribe connection");
console.log(cancel);
}
});
},
requestStream(url) {
if (this.socket) {
this.socket
.requestStream({
data: url + " from client",
metadata: String.fromCharCode(url.length) + url
})
.subscribe({
onComplete: () => console.log("requestStream done"),
onError: error => {
console.log("got error with requestStream");
console.error(error);
},
onNext: value => {
// console.log("got next value in requestStream..");
console.log("got data from sever");
console.log(value.data);
},
// Nothing happens until `request(n)` is called
onSubscribe: sub => {
console.log("subscribe request Stream!");
sub.request(2147483647);
// sub.request(3);
}
});
} else {
console.log("not connected...");
}
}
I can see both messages in Google Chrome DevTools -> Network -> rsocket. So the client receives them but I can't catch in the code the one sent by RSocketRequester.
It seems that the server uses fireAndForget method. How to handle it on the client side?
As #VladMamaev said, we can provide a responder to the client like in this example https://github.com/rsocket/rsocket-js/blob/master/packages/rsocket-examples/src/LeaseClientExample.js#L104
For me, fireAndForget method is enough.
export class EchoResponder {
constructor(callback) {
this.callback = callback;
}
fireAndForget(payload) {
this.callback(payload);
}
}
import { EchoResponder } from "~/assets/EchoResponder";
...
const messageReceiver = payload => {
//do what you want to do with received message
console.log(payload)
};
const responder = new EchoResponder(messageReceiver);
connect() {
const transport = new RSocketWebSocketClient({
url: "ws://localhost:8080/rsocket"
});
const client = new RSocketClient({
serializers: {
data: JsonSerializer,
metadata: IdentitySerializer
},
setup: {
keepAlive: 60000,
lifetime: 180000,
dataMimeType: "application/json",
metadataMimeType: "message/x.rsocket.routing.v0"
},
responder: responder,
transport
});

Hub handshake failed with error 'WebSocket is not in the OPEN state' during start(). Stopping HubConnection

When trying to do a user count I get the error web socket is not in open state, I have Saaskit as well for mutitenancy could that be the cause?
I have tried specifieng UseWebsockets in the startup.cs with no luck
{
private static int UserCount;
public override Task OnConnectedAsync()
{
UserCount++;
base.OnConnectedAsync();
this.Clients.All.SendAsync("updateUserCount", UserCount);
return Task.CompletedTask;
}
public override Task OnDisconnectedAsync(Exception exception)
{
UserCount--;
base.OnDisconnectedAsync(exception);
this.Clients.All.SendAsync("updateUserCount", UserCount);
return Task.CompletedTask;
}
}```
```<script>
document.addEventListener('DOMContentLoaded', function () {
}
function onConnectionError(error) {
if (error && error.message) {
console.error(error.message);
}
}
var connection = new
signalR.HubConnectionBuilder().withUrl('/adminHub')
.configureLogging(signalR.LogLevel.Debug).build();
connection.start()
.then(function () {
onConnected(connection);
})
.catch(function (error) {
console.error(error.message);
});
});
</script>```
Debug: Sending handsha`enter code here`ke request.
Debug: Hub handshake failed with error 'WebSocket is not in the OPEN state' during start(). Stopping HubConnection.
HttpConnection.stopConnection(undefined) called while in state Disconnecting.
Connection disconnected with error 'WebSocket is not in the OPEN state'.
HubConnection.connectionClosed(WebSocket is not in the OPEN state) called while in state Connecting.
I know it is late response but this worked for me:
after calling start on connection.
connection.start()
.then(function (data) {
console.log(data);
}).catch(function (err) {
console.log(err);
});
add this property to webSocket Object:
Object.defineProperty(window.WebSocket, 'OPEN', { value: 1, });
Known Issue

SignalR after page refresh doesn't work properly

I am using SignalR in my angular5 website for presenting lock for documents. I am storing hub connection in data service and soon ad user logged in, I will start the connection. In each component which I need hub connection, I have an Observable and after the connection established, It listens to the hub. Everything is working properly. But after refreshing page, it will not show the result of SignalR command. If I click or mouse over on that page, then it will show the result of SignalR!
This is the code which run after login:
startConnection(): void {
//Create the hub connection for SignalR
this.dataService.connection = $.hubConnection(this.dataService.getServerConn());
this.dataService.authProxy = this.dataService.connection.createHubProxy('auth');
this.dataService.authProxy.on('handler', () => { });
this.dataService.authProxyCreated = false;
this.dataService.connection.qs = { "AuthenticationToken": sessionStorage.getItem('UMToken') };
if (this.dataService.connection.state != $.signalR.connectionState.connected)
this.dataService.connection.start().done(() => {
console.log('Connected to SignalR hub!');
}).catch((error: any) => {
console.log('Hub error -> ' + error);
});
}
and this is the code in component which listen to the hub:
ngOnInit() {
//SignalR
if (this.storeDataService.connection.state === $.signalR.connectionState.connected)
this.registerSignalR();
this.storeDataService.connection.stateChanged((change) => {
if (change.newState === $.signalR.connectionState.connected)
this.registerSignalR();
});
}
ngOnDestroy() {
this.storeDataService.authProxy.off('lockAuth');
this.storeDataService.authProxy.off('unlockAuth');
}
registerSignalR() {
this.storeDataService.authProxy.on('lockAuth', (authNo: string, username: string) => {
var auth = this.queueList.data.find(p => p.AuthNo == authNo);
if (auth) {
auth.LockedOn = new Date();
auth.LockedByUserName = username;
}
});
this.storeDataService.authProxy.on('unlockAuth', (authNo: string) => {
var auth = this.queueList.data.find(p => p.AuthNo == authNo);
if (auth) {
auth.RmiLockedOn = null;
}
});
}
This is also the code in edit page which invoke lock:
if (this.dataService.connection.state === $.signalR.connectionState.connected) {
this.dataService.authProxy.invoke('lock', this.authNo, this.userService.userName, this.userService.userId);
}
this.dataService.connection.stateChanged((change) => {
if (change.newState === $.signalR.connectionState.connected) {
this.dataService.authProxy.invoke('lock', this.authNo, this.userService.userName, this.userService.userId);
}
});

Request Data from MSSQL with Node.js -- Error

I want to connect and Request from MSSQL using nodejs to link it with magento.
I Am trying to fix it for days now but it ends on the same way...
This is my Error Code:
Connected
{ RequestError: Requests can only be made in the LoggedIn state, not the Connecting state
at RequestError (C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\errors.js:34:12)
at Connection.makeRequest (C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\connection.js:1423:33)
at Connection.execSql (C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\connection.js:1194:19)
at executeStatement (C:\Workspace\Visual-Code\nodeApi\nodeapi.js:41:20)
at Connection.<anonymous> (C:\Workspace\Visual-Code\nodeApi\nodeapi.js:14:9)
at emitOne (events.js:116:13)
at Connection.emit (events.js:211:7)
at Connection.socketError (C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\connection.js:869:14)
at C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\connection.js:739:25
at GetAddrInfoReqWrap.callback (C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\connector.js:68:18)
message: 'Requests can only be made in the LoggedIn state, not the
Connecting state',
code: 'EINVALIDSTATE' }
I searched a lot and found similar problems but nothing solved it...
This is my Code maybe you can help me Spot the mistake.
var Connection = require('tedious').Connection;
var config = {
userName: 'Cool userName',
password: 'awesome password',
server: 'amazing server',
options: {
database: 'database',
}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement();
});
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
function executeStatement() {
request = new Request("select * from Artikelstamm;", function(err) {
if (err) {
console.log(err);}
});
var result = "";
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
result+= column.value + " ";
}
});
console.log(result);
result ="";
});
request.on('done', function(rowCount, more) {
console.log(rowCount + ' rows returned');
});
connection.execSql(request);
}
Set Firewall rule to your DB by adding CleintIP. In Azure SQLDB, there is SET FIREWALL RULE button. You can use it to add IP.
Add this event to your request
request.on("requestCompleted", function () {
connection.close();
resolve(result);
});