這裏沒有對onOpen、onClose、onError作案例,生產環境須要具有。json
1.客戶端async
只推送不接收數據tcp
建立WebSocketClient類ide
1 class WebSocketClient 2 { 3 WebSocket ws; 4 string host; 5 string port; 6 public WebSocketClient() 7 { 8 string[] tcpPoint = XMLHelper.getArrayHost("/host/tcphost"); 9 host = tcpPoint[0]; 10 port = tcpPoint[1]; 11 ws = new WebSocket("ws://" + host + ":" + port); 12 ws.Connect(); 13 } 14 15 public bool ConnState() 16 { 17 if (ws.ReadyState==WebSocketState.Open) 18 { 19 return true; 20 } 21 return false; 22 } 23 24 public void SendData(string json) 25 { 26 ws.Send(json); 27 } 28 }
2.服務端spa
建立Chat類,接收數據code
1 class Chat:WebSocketBehavior 2 { 3 protected override async Task OnMessage(MessageEventArgs e) 4 { 5 6 StreamReader reader = new StreamReader(e.Data); 7 string text = reader.ReadToEnd(); 8 try 9 { 10 //業務處理 11 } 12 catch (Exception exception) 13 { 14 Console.WriteLine(exception); 15 } 16 } 17 }
Mainblog
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 int port=8088;//監聽端口號 6 var wsServer = new WebSocketServer(null, port); 7 wsServer.AddWebSocketService<Chat>("/"); 8 wsServer.Start(); 9 Console.WriteLine("開啓" + port + "端口WebSocket監聽..."); 10 11 Console.ReadKey(true); 12 wsServer.Stop(); 13 } 14 }