AdSense

網頁

2022/12/10

React WebSocket Go發收訊息

React與Go WebSocket發收訊息範例。


範例環境:

  • Go 1.19
  • React 18


事前要求

請先參考以下了解必要概念:



Go

參考「Golang WebSocket hello world」建立WebSocket server,WebSocket URL為http:localhost:8080/echo


React

建立React應用程式網址為http:localhost:3000

App.js內容如下,建立ComponentMessage

App.js

import { useEffect, useState } from "react";
import './App.css';

import * as React from 'react';

function App() {
  return (
      <Message/>
  );
}

const ws = new WebSocket('ws://localhost:8080/echo'); // get WebSocket connection object

const Message = () => {
  const [input, setInput] = useState('') // 'input' store data sending to WebScoket Server
  const [message, setMessage] = useState('') // 'message'store data received from WebSocket Server

  const handleChange = (event) => { // when <input> value changing, store the value to 'input' state
    setInput(event.target.value);
  };

  const handleClick = () =>  { // when clicking Send button, send stored value of 'input' to WebSocket Server
    ws.send(input)
  }

  useEffect(() => {
    ws.addEventListener('message', (event) => { // listen WebSocket message event to receive data from WebSocket Server
      setMessage(event.data)
    })
  },[])

  return (
    <div>
      <div>
        <input onChange={handleChange}/>
        <button onClick={handleClick}>Send</button>
      </div>
      <div>{message}</div>
    </div>
  )
}

export default App;

github


使用new WebSocket('ws://localhost:8080/echo')建立連線物件WebSocket

在欄位輸入文字時handleChange函式會將欄位值儲存至Message.state.input

點擊Send按鈕時handleClick函式會將Message.state.input的值透過WebSocket.send()送至Go WebSocket server。

useEffect()使用WebSocket.addEventListener('message', listerer)監聽當有訊息送來時呼叫setMessages()更新Message.state.message狀態useEffect()第二個參數為dependency array,使用一個空陣列避免因狀態改變造成的無窮迴圈。


測試

啟動Go及React程式,在瀏覽器輸入http://localhost:3000開啟頁面,在欄位輸入訊息按Send會將訊息送至Go WebSocket server,然後同樣的訊息會再由Go WebSocket server寫出至React的WebSocket client並顯示在輸入欄位下方。

沒有留言:

AdSense