创建连接
ClientWebSocket socket = new ClientWebSocket();
string url = $"ws://{ip}:{port}";
bool createUri = Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out Uri uri);
if (createUri)
{
var task = socket.ConnectAsync(uri, CancellationToken.None);
task.Wait(1000);
if (socket.State == WebSocketState.Open)
{
Debug.Log("连接成功!");
}
}
信息接收
byte[] arrry = new byte[1024];
ArraySegment<byte> buffer = new ArraySegment<byte>(arrry);
var task = socket.ReceiveAsync(buffer, CancellationToken.None);
task.Wait(1000);
string msg = Encoding.UTF8.GetString(buffer.Array, 0, task.Result.Count);
信息发送
ArraySegment<byte> array = new ArraySegment<byte>(Encoding.UTF8.GetBytes(msg));
var task = socket.SendAsync(array, WebSocketMessageType.Binary, true, CancellationToken.None);
task.Wait(2000);
断开连接
var task = socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
task.Wait(2000);