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受信メッセージ = evt.data; document.getElementById(showMes).value+=evt.data+/n;};ws.onclose = function() {alert(切断);};} else {alert(ブラウザは WebSocket をサポートしていません);}function login (){変数message=document.getElementById(name).value+:+document.getElementById(mes).value;socket.send(message);}</script></head><body><textarea rows=3cols=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;}private void Form1_Load(object sender, EventArgs e){//すべての接続を保存 var allSockets = new List<IWebSocketConnection>();//サーバーを初期化します。 var server = new WebSocketServer(ws://0.0.0.0:8181);//リスニングを開始します。server.Start(socket =>{//クライアント接続によってソケットがトリガーされます。 OnOpen = () =>{textBox3.Text +=ソケット.ConnectionInfo.ClientIpAddress + Connection/r/n;allSockets.Add(socket);};//クライアントの切断がトリガーされます。ソケット);};//クライアントから送信されたメッセージを受信します。socket.OnMessage = message =>{textBox3.Text += socket.ConnectionInfo.ClientIpAddress + メッセージを送信しました: + message + /r/n;//受信したメッセージをすべてのクライアントに送信します allSockets.ToList().ForEach(s => s.Send(message));}; ;}}}要約する
上記は、編集者が紹介した HTML5 ベースの WebSocket のサンプル コードです。ご質問があれば、メッセージを残してください。編集者がすぐに返信します。また、VeVb武道サイトを応援してくださった皆様、誠にありがとうございました!