一、C# webAPI客户端webSocket的基本用法
using System.Net.WebSockets;
private ClientWebSocket webSocket = new ClientWebSocket();
private static String SocketPath = "ws://xxx.x.x.x:8085";
[HttpPost]
public async Task<IHttpActionResult> ReportInfo(){
try
{
if (webSocket.State != WebSocketState.Open)
{
//连接服务器,如果远程服务器未开启,这句话会报错:无法连接到远程服务器
await webSocket.ConnectAsync(new Uri(SocketPath), CancellationToken.None);
}
//上报对象转为json字符串;
string SendJson = JsonConvert.SerializeObject(ReportInfos);
//发送的数据
var sendBytes = Encoding.UTF8.GetBytes("WebApiJson:" + SendJson);
var bsend = new ArraySegment<byte>(sendBytes);
//发送信息
await webSocket.SendAsync(bsend, WebSocketMessageType.Text, true, CancellationToken.None);
//关闭连接
if (webSocket.State == WebSocketState.Open)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "1", CancellationToken.None);//关闭连接
}
}
catch (Exception ex)
{
messageinfo.code = 2;
messageinfo.msg = ex.Message;
}
finally
{
webSocket.Dispose();
}
}