Как реагирует js как клиент websocket?
Я хочу создать приложение клиент-сервер на основе Websocket. В этом я создал node js websocket server, который ждет клиентов. Теперь я хочу создать клиент реакции js websocket. Я использую response js как websocket, потому что я должен постоянно отображать элементы, которые сервер отправляет как простое текстовое сообщение.
Я поражен внедрением js-ответа как клиента websocket. Как он должен работать как клиент websocket и как он будет отправлять запрос на сервер websocket так:
'ws://localhost:1234'
Я хочу узнать больше о клиенте websocket и также хочу решить эту проблему?
Ответы
Ответ 1
Таким образом, очень простой пример без особых затрат потребует две вещи:
компонент со ссылкой на соединение через веб-сокет
прослушиватель событий в соединении, который обновляет состояние компонента
когда приходит сообщение
Демо: http://jsfiddle.net/69z2wepo/47360/
Демонстрация (2019): http://jsfiddle.net/643atLce/
class Echo extends React.Component {
constructor(props){
super(props);
this.state = { messages : [] }
}
componentDidMount(){
// this is an "echo" websocket service
this.connection = new WebSocket('wss://echo.websocket.org');
// listen to onmessage event
this.connection.onmessage = evt => {
// add the new message to state
this.setState({
messages : this.state.messages.concat([ evt.data ])
})
};
// for testing purposes: sending to the echo service which will send it back back
setInterval( _ =>{
this.connection.send( Math.random() )
}, 2000 )
}
render() {
// slice(-5) gives us the five most recent messages
return <ul>{ this.state.messages.slice(-5).map( (msg, idx) => <li key={'msg-' + idx }>{ msg }</li> )}</ul>;
}
};
Ответ 2
Просто создайте программу отдыха с сервера и создайте соединение на веб-странице.
var connection = new WebSocket('ws://localhost/echo', ['soap', 'xmpp']);
opening the connection
connection.onopen = function () {
connection.send('Ping'); //
};
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
//to receive the message from server
connection.onmessage = function (e) {
console.log('Server: ' + e.data);
};
// Sending String
connection.send('your message');
На стороне сервера вы получите сеанс и сообщение, поэтому вы можете общаться с N сеансами.
Ответ 3
В папке "Реакция проекта" в App.js добавьте соединение с веб-сокетом и прослушайте сообщения, поступающие с сервера веб-сокета.
class App extends React.Component{
constructor(){
super();
this.state={
endpoint:"ws://localhost:1234",
messages:[]
}
}
componentDidMount(){
//initialize connection
const ws = new WebSocket(this.state.endpoint)
ws.onopen = () =>{
//send any msg from Client if needed
ws.send(JSON.stringify(temp))
}
//save whatever response from client
ws.onmessage = evt =>{
this.setState({
message:this.state.message.concat(evt.data)
})
}
}
render(){
return(
<div>
<p>{this.state.message.map(items=><li>{items}</li>)}</p>
</div>
)}
}