@rodger.botsford
const socket = new WebSocket('ws://localhost:8080');
socket.send('Hello Server!');
socket.addEventListener('open', () => { console.log('WebSocket connection has been established.'); });
socket.addEventListener('close', () => { console.log('WebSocket connection has been closed.'); });
socket.addEventListener('error', (event) => { console.error('WebSocket connection error:', event); });
socket.addEventListener('message', (event) => { console.log('Message from server:', event.data); });
socket.close();
@rodger.botsford
Примеры использования WebSocket API в JavaScript:
1
|
var connection = new WebSocket('ws://localhost:1234'); |
1
|
connection.send('Hello, server!'); |
1 2 3 |
connection.onmessage = function(event) { console.log('Received message: ' + event.data); }; |
1 2 3 |
connection.onerror = function(error) { console.error('WebSocket Error ' + error); }; |
1
|
connection.close(); |
1 2 3 |
if (connection.readyState === WebSocket.OPEN) { // WebSocket соединение открыто и готово к использованию } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import React, { Component } from 'react'; class WebSocketComponent extends Component { state = { messages: [], currentMessage: '' }; constructor(props) { super(props); this.connection = new WebSocket('ws://localhost:1234'); } componentDidMount() { this.connection.onmessage = this.handleMessage; } componentWillUnmount() { this.connection.close(); } handleMessage = (event) => { const messages = [...this.state.messages]; messages.push(event.data); this.setState({ messages }); } handleInput = (event) => { this.setState({ currentMessage: event.target.value }); } handleSubmit = (event) => { event.preventDefault(); this.connection.send(this.state.currentMessage); this.setState({ currentMessage: '' }); } render() { const { messages, currentMessage } = this.state; return ( {messages.map((message, index) => ( {message} ))} Send ); } } export default WebSocketComponent; |