MessageWebSocket
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Windows; using Windows.Networking; using Windows.Networking.Sockets; using Windows.Storage; using Windows.Storage.Streams; namespace WebSocketClient { class Program { static void Main() { var socket = new MessageWebSocket(); socket.MessageReceived += Socket_MessageReceived; new Func<Task>(async () => { await socket.ConnectAsync(new Uri("wss://echo.websocket.org")); await Socket_SendMessageAsync(socket, "Hello World!"); })(); Console.ReadKey(true); } private static void Socket_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { using (var dataReader = args.GetDataReader()) { dataReader.UnicodeEncoding = UnicodeEncoding.Utf8; string message = dataReader.ReadString(dataReader.UnconsumedBufferLength); Console.WriteLine("Received: {0}", message); } } private static async Task Socket_SendMessageAsync(MessageWebSocket socket, string message) { using (var dataWriter = new DataWriter(socket.OutputStream)) { dataWriter.WriteString(message); await dataWriter.StoreAsync(); dataWriter.DetachStream(); Console.WriteLine("Sent: {0}", message); } } } }
posted on 2019-08-26 20:48 JebediahKerman 阅读(702) 评论(0) 编辑 收藏 举报