因为服务端用蛋疼的websocket通讯,客户端用socket好像用不了(反正我不会),然后尝试使用ClientWebSocket进行开发,下面程序在关闭连接的时候有问题,暂时将就着
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Threading;
using System.Net;
using System.Net.WebSockets;
public class WebTCPSocket
{
ClientWebSocket m_webSocket;
ArraySegment<byte> m_recvBuffer = new ArraySegment<byte>(new byte[1024]);
public Action<byte[]> m_RecvData;
public async void Connect(string _uri,Action _finish)
{
m_webSocket = new ClientWebSocket();
await m_webSocket.ConnectAsync(new Uri(_uri),CancellationToken.None);
receive();
if(_finish!=null)
{
_finish();
}
}
public async void Send(byte[] _data,Action<Result> _finish)
{
if(m_webSocket!=null)
{
if(m_webSocket.State==WebSocketState.Open)
{
await m_webSocket.SendAsync(new ArraySegment<byte>(_data),WebSocketMessageType.Text,true,CancellationToken.None);
if(_finish!=null)
{
_finish(Result.Success);
}
}
else
{
Debug.LogErrorFormat("[WebTCPSocket.Send]State={0},{1},{2}",m_webSocket.State,m_webSocket.CloseStatus,m_webSocket.CloseStatusDescription);
if(_finish!=null)
{
_finish(Result.Err);
}
}
}
else
{
Debug.LogError("[WebTCPSocket.Send]m_webSocket为空");
if(_finish!=null)
{
_finish(Result.NotConnected);
}
}
}
public async void Close()
{
if(m_webSocket!=null)
{
// if(m_webSocket.State==WebSocketState.Open)
// {
// await m_webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure,"",CancellationToken.None);
// m_webSocket.Dispose();
// }
// else
// {
// Debug.LogErrorFormat("[WebTCPSocket.Close]State={0},{1},{2}",m_webSocket.State,m_webSocket.CloseStatus,m_webSocket.CloseStatusDescription);
// }
await m_webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure,"",CancellationToken.None);
// await m_webSocket.CloseAsync(WebSocketCloseStatus.Empty,"",CancellationToken.None);
m_webSocket.Dispose();
Debug.Log("[WebTCPSocket.Close]服务器关闭");
}
else
{
Debug.LogError("[WebTCPSocket.Close]m_webSocket为空");
}
}
async void receive()
{
if(m_webSocket!=null)
{
if(m_webSocket.State==WebSocketState.Open)
{
byte[] data = null;
try
{
WebSocketReceiveResult result = await m_webSocket.ReceiveAsync(m_recvBuffer,CancellationToken.None);
data = new byte[result.Count];
Array.Copy(m_recvBuffer.Array,data,data.Length);
}
catch
{
Debug.LogWarningFormat("[WebTCPSocket.receive]State={0},{1},{2}",m_webSocket.State,m_webSocket.CloseStatus,m_webSocket.CloseStatusDescription);
}
if(m_RecvData!=null)
{
m_RecvData(data);
}
receive();
}
// else
// {
// Debug.LogErrorFormat("[WebTCPSocket.receive]State={0},{1},{2}",m_webSocket.State,m_webSocket.CloseStatus,m_webSocket.CloseStatusDescription);
// }
}
else
{
Debug.LogError("[WebTCPSocket.receive]m_webSocket为空");
}
}
public enum Result
{
Success,
NotConnected,
Err
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////20181012
日乐购 上面的鬼东西在连续发送几次消息会断开连接 蛋疼
最后使用BestHTTP插件的WebSocket功能