1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | using System; using System.Net.WebSockets; using System.Text; using System.Threading; class Client { static void Main( string [] args) { var client = new ClientWebSocket(); client.ConnectAsync( new Uri( "ws://echo.websocket.org" ), CancellationToken.None).Wait(); //client.ConnectAsync(new Uri("ws://localhost:4567/ws/"), CancellationToken.None).Wait(); StartReceiving(client); string line; while ((line = Console.ReadLine()) != "exit" ) { var array = new ArraySegment< byte >(Encoding.UTF8.GetBytes(line)); client.SendAsync(array, WebSocketMessageType.Text, true , CancellationToken.None); } } static async void StartReceiving(ClientWebSocket client) { while ( true ) { var array = new byte [4096]; var result = await client.ReceiveAsync( new ArraySegment< byte >(array), CancellationToken.None); if (result.MessageType == WebSocketMessageType.Text) { string msg = Encoding.UTF8.GetString(array, 0, result.Count); Console.ForegroundColor = ConsoleColor.DarkBlue; Console.WriteLine( "--> {0}" , msg); Console.ForegroundColor = ConsoleColor.DarkGray; } } } } |
联系客服