Web Socket

Web Socket

2021/05/27 (增加連結)

Websocket

Nest.js

React

事件處理 (onopen, onmessage, onclose, onerror)

ws = new WebSocket(URL)


componentDidMount() {

this.ws.onopen = () => {

// on connecting, do nothing but log it to the console

console.log('connected')

}


this.ws.onmessage = evt => {

// on receiving a message, add it to the list of messages

const message = JSON.parse(evt.data)

this.addMessage(message)

}


this.ws.onclose = () => {

console.log('disconnected')

// automatically try to reconnect on connection loss

this.setState({

ws: new WebSocket(URL),

})

}

}

送出訊息

submitMessage = messageString => {

// on submitting the ChatInput form, send the message, add it to the list and reset the input

const message = { name: this.state.name, message: messageString }

this.ws.send(JSON.stringify(message))

this.addMessage(message)

}


Redux

Node.js

Java

javax.websocket

@ServerEndpoint(value = "/chat/{username}")

public class ChatEndpoint {

@OnOpen

public void onOpen(Session session) throws IOException {

// Get session and WebSocket connection

}

@OnMessage

public void onMessage(Session session, Message message) throws IOException {

// Handle new messages

}

@OnClose

public void onClose(Session session) throws IOException {

// WebSocket connection closes

}

@OnError

public void onError(Session session, Throwable throwable) {

// Do error handling here

}

}

java.net.http.WebSocket

Spring Boot

Android