html websocket的基本使用
<! DOCTYPE html >
< html lang = " en" > < head> < meta charset = " UTF-8" /> < meta http-equiv = " X-UA-Compatible" content = " IE=edge" /> < meta name = " viewport" content = " width=device-width, initial-scale=1.0" /> < style> div { width : 200px; height : 200px; border : 1px solid #30897c; } </ style> < title> 聊天室</ title> </ head> < body> < input type = " text" placeholder = " 输入你的内容" name = " " id = " " /> < button> 发送请求</ button> < div> </ div> </ body>
</ html> < script> var input = document. querySelector ( "input" ) ; var button = document. querySelector ( "button" ) ; var div = document. querySelector ( "div" ) ; var socket = new WebSocket ( "ws://localhost:3000" ) ; socket. addEventListener ( "open" , function ( ) { div. innerHTML = "连接服务成功了!" ; } ) ; button. addEventListener ( "click" , ( ) => { var value = input. value; socket. send ( value) ; } ) ; socket. addEventListener ( "message" , ( e ) => { console. log ( e. data) ; div. innerHTML = e. data; } ) ; socket. addEventListener ( "close" , ( ) => { console. log ( "服务器断开。。。" ) ; } ) ;
</ script>