HTML5 기반 WebSocket의 예제 코드
클라이언트 코드:
<html><head><script>var 소켓;if(창의 WebSocket) {var ws = new WebSocket(ws://127.0.0.1:8181);socket = ws;ws.onopen = function() {console. log('연결 성공');};ws.onmessage = function(evt) {var received_msg = evt.data; document.getElementById(showMes).value+=evt.data+/n;};ws.onclose = function() {alert(disconnected);};} else {alert(브라우저는 WebSocket을 지원하지 않습니다);}함수 로그인(){ var message=document.getElementById(name).value+:+document.getElementById(mes).value;socket.send(message);}</script></head><body><textarea 행=3 cols=30 id= showMes style=width:300px;height:500px;></textarea><br/><label>이름</label><input type=text id=name/><br/><label>메시지</label><input type=text id=mes/><button onclick=login();>보내기</button></body></ HTML>
winform 서버 코드:
참고: Fleck 패키지를 먼저 소개해야 합니다.
System 사용;System.Collections.Generic 사용;System.Linq 사용;System.Windows.Forms 사용;Fleck 사용;네임스페이스 소켓 서비스{공개 부분 클래스 Form1: Form{public Form1(){InitializeComponent();CheckForIllegalCrossThreadCalls = false;}비공개 void Form1_Load(object sender, EventArgs e){//모든 연결 저장 var allSockets = new List<IWebSocketConnection>();//서버 초기화 var server = new WebSocketServer(ws://0.0.0.0:8181);//수신 서버 시작.Start(socket =>{//클라이언트 연결이 소켓을 트리거합니다. OnOpen = () =>{textBox3.Text += 소켓.ConnectionInfo.ClientIpAddress + Connection/r/n;allSockets.Add(socket);};//클라이언트 연결 끊김이 소켓.OnClose = () =>{textBox3.Text += 소켓.ConnectionInfo.ClientIpAddress + Disconnect/r/n ;allSockets.Remove( 소켓);};//클라이언트에서 보낸 메시지를 받습니다.socket.OnMessage = message =>{textBox3.Text += 소켓.ConnectionInfo.ClientIpAddress + 메시지 보내기: + 메시지 + /r/n;//받은 메시지를 모든 클라이언트에게 보내기 allSockets.ToList().ForEach(s => s.Send(message));}) ;}}}요약
위 내용은 에디터가 소개한 HTML5 기반의 WebSocket 예제 코드입니다. 궁금한 점이 있으시면 메시지를 남겨주시면 에디터가 시간 맞춰 답변해 드리겠습니다. 또한 VeVb 무술 웹사이트를 지원해 주신 모든 분들께 감사드립니다!