第一種方式
// 服務端:
// 客戶端:
//var ws = new clientwebsocket();
//await ws.connectasync(new uri("ws:"), cancellationtoken.none);
#region myregion
// 1. 使用.net4.5 自帶的websocket
//服務端:
// 客戶端:
//var ws = new clientwebsocket();
// await ws.connectasync(new uri("ws:"), cancellationtoken.none);
//2. 使用 websocket-sharp dll提供的 websocket(支援.net4.0)
//客戶端:
//_cainiaows = new websocket(wsurl);
// _cainiaows.onmessage += (sender, e) => onmessage(e.data);
// _cainiaows.connect();
// 3. 使用 socket 類(支援.net4.0)
第二種方式
//int port = 1234;
//string host = "127.0.0.1";
//ipaddress ip = ipaddress.parse(host);
//ipendpoint ipe = new ipendpoint(ip, port);
//socket ssocket = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
"監聽已經開啟,請等待");
receive message
//socket serversocket = ssocket.accept();
"連線已經建立");
//string recstr = "";
//byte recbyte = new byte[4096];
//int bytes = serversocket.receive(recbyte, recbyte.length, 0);
//recstr += encoding.ascii.getstring(recbyte, 0, bytes);
send message
"伺服器端獲得資訊:", recstr);
//string sendstr = "send to client :hello";
//byte sendbyte = encoding.ascii.getbytes(sendstr);
sendbyte.length, 0);
//int port = 1234;
//string host = "127.0.0.1";//伺服器端ip位址
//ipaddress ip = ipaddress.parse(host);
//ipendpoint ipe = new ipendpoint(ip, port);
// socket clientsocket = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
send message
//string sendstr = "begin#70";
//byte sendbytes = encoding.ascii.getbytes(sendstr);
receive message
//string recstr = "";
//byte recbytes = new byte[4096];
//int bytes = clientsocket.receive(recbytes, recbytes.length, 0);
//recstr += encoding.ascii.getstring(recbytes, 0, bytes);
recstr);
實時響應
using system;
using system.net;
using system.net.sockets;
using system.text;
using system.threading;
using system.net.websockets;
using system.io;
namespace websockettest
catch (exception ex)
console.read();}}
public static async void gg(clientwebsocket clientwebsocket)
while (!result.endofmessage);
ms.seek(0, seekorigin.begin);
if (result.messagetype == websocketmessagetype.text)}}
}
Tcp Socket非同步通訊例項
socket客戶端實體類,作用傳送和接收資料報 public class sockethelper catch argumentexception ae catch socketexception ex region methods socket通訊機連線函式 public bool connect...
非同步通訊例項(一)Server
using system using system.drawing using system.collections using system.componentmodel using system.windows.forms using system.data using system.text ...
基於Ws的WebSocket通訊例項解析
websocket的目標是在乙個單獨的持久鏈結上提供全雙工 雙向通訊。在js建立websocket之後,會有乙個http傳送到瀏覽器以發起鏈結,在取得伺服器響應後,建立的連線會使用http公升級從http協議交換為websocket協議,也就是說,使用標準的http協議無法實現websockts,只...