Issue
When using stomp.js and sockjs from within Javascript, I can connect well with a Spring Boot backend.
When using stompjs and sockjs from with Angular5, I keep on getting these errors:
InvalidStateError: The connection has not been established yet
Is there a workaround? Just adding the sockjs.min.js, as mentioned in this post, was not helping.
The detailed log is:
Setting up connection/1 main.3388a5e3a20e64e3bdb8.bundle.js:1 Setting
up connection/2 main.3388a5e3a20e64e3bdb8.bundle.js:1 Going to
subscribe … main.3388a5e3a20e64e3bdb8.bundle.js:1 Opening Web
Socket… main.3388a5e3a20e64e3bdb8.bundle.js:1 >>> SEND
destination:/app/chat.addUser content-length:29{“sender”:”me”,”type”:”JOIN”} main.3388a5e3a20e64e3bdb8.bundle.js:1
ERROR Error: Uncaught (in promise): Error: InvalidStateError: The
connection has not been established yet Error: InvalidStateError: The
connection has not been established yet
at r.send (scripts.d6f701ecf84f24372966.bundle.js:1)
My code in Angular (translated from Javascript) is:
let ws = new SockJS(this.serverUrl);
this.stompClient = Stomp.over(ws);
let that = this;
console.log('Setting up connection/2');
console.log('Going to subscribe ... ');
this.stompClient.connect({}, function (frame) {
console.log('Going to subscribe ... ');
that.stompClient.subscribe('/topic/public', (payload) => {
console.log('Subscribe: Incoming message: ' + payload.body);
if (payload.body) {
let message = JSON.parse(payload.body);
if (message.sender === 'MyBot') {
this.createAndAddChat('you', message.content);
} else {
this.createAndAddChat('me', message.content);
}
console.log('New message arrived: ' + payload.body);
}
},
error => {
console.log( 'Subscribe: error: ' + error)
},
() => {
console.log( 'Subscribe, On complete')
});
});
this.stompClient.send("/app/chat.addUser", {},
JSON.stringify({sender: 'me', type: 'JOIN'})
)
Solution
The send method is now called directly after starting (!) the asynchronous get-connection call. That’s wrong.
There are 2 solutions:
- Good: Put the send call within the async-body of the get-connection. So after the connection is made, call the send method.
- Not optimal: Wait for some time to have the async get-connection to complete.
Answered By – tm1701
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0
Issue
When using stomp.js and sockjs from within Javascript, I can connect well with a Spring Boot backend.
When using stompjs and sockjs from with Angular5, I keep on getting these errors:
InvalidStateError: The connection has not been established yet
Is there a workaround? Just adding the sockjs.min.js, as mentioned in this post, was not helping.
The detailed log is:
Setting up connection/1 main.3388a5e3a20e64e3bdb8.bundle.js:1 Setting
up connection/2 main.3388a5e3a20e64e3bdb8.bundle.js:1 Going to
subscribe … main.3388a5e3a20e64e3bdb8.bundle.js:1 Opening Web
Socket… main.3388a5e3a20e64e3bdb8.bundle.js:1 >>> SEND
destination:/app/chat.addUser content-length:29{«sender»:»me»,»type»:»JOIN»} main.3388a5e3a20e64e3bdb8.bundle.js:1
ERROR Error: Uncaught (in promise): Error: InvalidStateError: The
connection has not been established yet Error: InvalidStateError: The
connection has not been established yet
at r.send (scripts.d6f701ecf84f24372966.bundle.js:1)
My code in Angular (translated from Javascript) is:
let ws = new SockJS(this.serverUrl);
this.stompClient = Stomp.over(ws);
let that = this;
console.log('Setting up connection/2');
console.log('Going to subscribe ... ');
this.stompClient.connect({}, function (frame) {
console.log('Going to subscribe ... ');
that.stompClient.subscribe('/topic/public', (payload) => {
console.log('Subscribe: Incoming message: ' + payload.body);
if (payload.body) {
let message = JSON.parse(payload.body);
if (message.sender === 'MyBot') {
this.createAndAddChat('you', message.content);
} else {
this.createAndAddChat('me', message.content);
}
console.log('New message arrived: ' + payload.body);
}
},
error => {
console.log( 'Subscribe: error: ' + error)
},
() => {
console.log( 'Subscribe, On complete')
});
});
this.stompClient.send("/app/chat.addUser", {},
JSON.stringify({sender: 'me', type: 'JOIN'})
)
Solution
The send method is now called directly after starting (!) the asynchronous get-connection call. That’s wrong.
There are 2 solutions:
- Good: Put the send call within the async-body of the get-connection. So after the connection is made, call the send method.
- Not optimal: Wait for some time to have the async get-connection to complete.
Answered By — tm1701
При использовании Stomp.js и sockjs из Javascript я могу хорошо подключиться к бэкэнду Spring Boot.
При использовании Stompjs и sockjs с Angular5 я продолжаю получать следующие ошибки:
InvalidStateError: соединение еще не установлено
Есть ли обходной путь? Простое добавление sockjs.min.js, как упоминалось в этом посте, не помогло.
Подробный журнал:
Setting up connection/1 main.3388a5e3a20e64e3bdb8.bundle.js:1 Setting
up connection/2 main.3388a5e3a20e64e3bdb8.bundle.js:1 Going to
subscribe … main.3388a5e3a20e64e3bdb8.bundle.js:1 Opening Web
Socket… main.3388a5e3a20e64e3bdb8.bundle.js:1 >>> SEND
destination:/app/chat.addUser content-length:29{«sender»:»me»,»type»:»JOIN»} main.3388a5e3a20e64e3bdb8.bundle.js:1
ERROR Error: Uncaught (in promise): Error: InvalidStateError: The
connection has not been established yet Error: InvalidStateError: The
connection has not been established yet
at r.send (scripts.d6f701ecf84f24372966.bundle.js:1)
Мой код в Angular (переведенный с Javascript):
let ws = new SockJS(this.serverUrl);
this.stompClient = Stomp.over(ws);
let that = this;
console.info('Setting up connection/2');
console.info('Going to subscribe ... ');
this.stompClient.connect({}, function (frame) {
console.info('Going to subscribe ... ');
that.stompClient.subscribe('/topic/public', (payload) => {
console.info('Subscribe: Incoming message: ' + payload.body);
if (payload.body) {
let message = JSON.parse(payload.body);
if (message.sender === 'MyBot') {
this.createAndAddChat('you', message.content);
} else {
this.createAndAddChat('me', message.content);
}
console.info('New message arrived: ' + payload.body);
}
},
error => {
console.info( 'Subscribe: error: ' + error)
},
() => {
console.info( 'Subscribe, On complete')
});
});
this.stompClient.send("/app/chat.addUser", {},
JSON.stringify({sender: 'me', type: 'JOIN'})
)
tm1701, 19 октября 2018 г., 21:41
3
6 384
1
Ответ:
Решено
Метод send теперь вызывается сразу после запуска (!) Асинхронного вызова get-connection. Это неверно.
Есть 2 решения:
- Хорошо: поместите вызов send в async-body get-connection. Итак, после того, как соединение установлено, вызовите метод отправки.
- Неоптимально: подождите некоторое время, пока асинхронное соединение get завершится.
tm1701, 20 октября 2018 г., 08:48
Интересные вопросы для изучения
Below are the demos and comments I wrote, in order to use websocket in the future, it looks a little more convenient=-=
<template>
<div>
<button @click="sendDevName('xxxxxxxx')">send</button>
{{data}}
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
data: null
}
},
// Execute initWebSocket() to initialize websocket after html loading
mounted () {
this.initWebSocket()
},
// Execute when leaving this layer, focus on it! ! !
destroyed: function () {
// Disconnect the websocket connection after leaving the route
this.websock.close()
},
methods: {
// Initialize websocket
initWebSocket () {
const path = 'ws://xxx.xxx.xxx.xxx:port number/xxxxx'// The ip address of websocket given by the background
this.websock = new WebSocket(path)
this.websock.onmessage = this.websocketOnMessage
this.websock.onopen = this.websocketOnOpen
this.websock.onerror = this.websocketOnError
this.websock.onclose = this.websocketClose
},
// Signal that the connection is established successfully
websocketOnOpen () {
console.log('initialized successfully')// After the connection is successful, you can write some callback functions here
},
// Reconnect after connection establishment failure
websocketOnError () {
// If an error is reported, you can reinitialize the websocket here, which is disconnected and reconnected
this.initWebSocket()
},
// data reception
websocketOnMessage (e) {
console.log(e)// The variable e is the data returned from the background, and the returned value can be processed in this function
this.data = e// Here I bind a data, data will display the things from the backend on the web page
},
// data transmission
websocketSend (Data) {
this.websock.send(Data)// The Data variable is what you want to say to the backend, and interact according to the interface document passed to you by the backend
},
// closed signal
websocketClose () {
console.log('Disconnect')
},
// Pass the parameters to the backend, here is another layer of encapsulation for websocketSend, you can delete the ones you don’t need
sendDevName (chooseDevice) {
console.log(chooseDevice)
this.websocketSend(chooseDevice)
}
}
}
</script>
Frontend click to send
The back-end server will receive the things in the mosaic
When the front end clicks the send button to trigger the websocketSend (Data) function, the back end will receive the message sent by the front end, and then send the information required by the front end according to the message from the front end. When something is sent, it will trigger the websocketOnMessage (e) function
The pits I stepped on when writing code
Uncaught InvalidStateError: Failed to execute ‘send’ on ‘WebSocket’: Still in CONNECTING state
This means that the websocket is still connected and the send method fails to be called
The reason is that when I initialize the websocket, I directly call send to talk to the background. At this time, the websocket may not be connected yet, and this error will be reported.
So I learned well, and I call out after the initialization is successful, there will be no problem
Popularize the status of websocket
Two properties of websocket: readyState and bufferedAmount.
According to the readyState attribute, the connection status of the webSocket can be judged. The value of this attribute can be the following:
0: corresponds to the constant CONNECTING (numeric value 0),
The connection is being established and has not been completed. The connection has not yet been established.
1: corresponds to the constant OPEN (numeric value 1),
The connection is successfully established and you can communicate. The WebSocket connection is established and communication is possible.
2: Corresponding constant CLOSING (numeric value 2)
The connection is in the process of closing handshake and will be closed soon. The connection is going through the closing handshake.
3: Corresponding constant CLOSED (numeric value 3)
The connection has been closed or not established at all. The connection has been closed or could not be opened.
Example:
var socket = new WebSocket(url);
if(socket.readyState!=1){
alert(«Not connected.»);
return;
}
According to bufferedAmount, you can know how many bytes of data are waiting to be sent. If the websocket has called the close method, this attribute will keep growing.
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.