標籤:檔案 inpu 搭建 開啟 技術 ini utf-8 發送 var
編寫用戶端代碼
1.建立一個*.html檔案。
ws = new WebSocket(‘ws://192.168.85.128:8086/Handler1.ashx?user=‘ + $("#user").val());
這個地方的IP和連接埠號碼對應著我們搭建在IIS上的WebSocket伺服器
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"/> <title></title> <script src="http://code.jquery.com/jquery-1.4.1.min.js"></script> <script> var ws; $().ready(function () { $(‘#conn‘).click(function () { //ws = new WebSocket(‘ws://‘ + window.location.hostname + ‘:‘ + window.location.port + ‘/Handler1.ashx?user=‘ + $("#user").val()); ws = new WebSocket(‘ws://192.168.85.128:8086/Handler1.ashx?user=‘ + $("#user").val()); //var host = ‘ws://192.168.85.128:8085/api/WSChat?user=‘+$("#user").val(); //var host = "ws://192.168.85.128:8085/api/WSChat"; //webSocket = new WebSocket(host); $(‘#msg‘).append(‘<p>正在串連</p>‘); ws.onopen = function () { $(‘#msg‘).append(‘<p>已經串連</p>‘); } ws.onmessage = function (evt) { $(‘#msg‘).append(‘<p>‘ + evt.data + ‘</p>‘); } ws.onerror = function (evt) { $(‘#msg‘).append(‘<p>‘ + JSON.stringify(evt) + ‘</p>‘); } ws.onclose = function () { $(‘#msg‘).append(‘<p>已經關閉</p>‘); } }); $(‘#close‘).click(function () { ws.close(); }); $(‘#send‘).click(function () { if (ws.readyState == WebSocket.OPEN) { ws.send($("#to").val() + "|" + $(‘#content‘).val()); } else { $(‘#tips‘).text(‘串連已經關閉‘); } }); }); </script></head><body> <div> <input id="user" type="text" /> <input id="conn" type="button" value="串連" /> <input id="close" type="button" value="關閉"/><br /> <span id="tips"></span> <input id="content" type="text" /> <input id="send" type="button" value="發送"/><br /> <input id="to" type="text" />目的使用者 <div id="msg"> </div> </div></body></html>
2.用戶端A和用戶端B通訊效果
在瀏覽器中分別開啟兩個視窗,左邊為用戶端A,右邊為用戶端B,點擊“串連”按鈕,AB用戶端分別與伺服器建立串連
填寫要發送的內容,即可看到A和B互相發送的資訊了,即實現了AB用戶端實現了WebSocket即時通訊。
在IIS上搭建WebSocket伺服器(三)