首頁>技術>

前端操作程式碼

import React,{Component} from 'react';import './App.css';class App extends Component { constructor(props){ super(props); this.state = {  websocketmsg:[] } }#初始化使用者名稱名連結會話 componentWillMount() { this.estabConnectWithWS("peabody") } estabConnectWithWS(username) { let wsUrl=`ws://127.0.0.1:8080/socketServer/`+username; const ws = new WebSocket(wsUrl);  let result = "";  #開啟會話 ws.onopen = function (e) { console.log('連線上 ws 服務端了'); ws.send(JSON.stringify({ flag: wsUrl, data: "Hello WebSocket!" })); }  #接收會話 ws.onmessage = (msg)=> {  let letmesg=msg.data if(letmesg.indexOf("close") != -1){  ws.close(); } let websocketmsg = this.state.websocketmsg; websocketmsg.push(letmesg) this.setState({websocketmsg:websocketmsg}); var div = document.getElementById('scrolldIV'); div.scrollTop = div.scrollHeight; };   ws.onclose = function (e) { console.log('ws 連線關閉了');  clearInterval(this.timer); this.timer = undefined; }  }render() { const websocketmsgmap=this.state.websocketmsg.map((item,index)=> <p>{item}</p> ) return ( <div id="scrolldIV" style={{overflow: 'scroll', height:'500px'}}> {websocketmsgmap} </div> )}}export default App;

最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • 零基礎安卓開發起步(三)