This commit is contained in:
2020-07-09 08:50:24 +08:00
parent 13d25f4707
commit c523462b82
1818 changed files with 174940 additions and 582 deletions

View File

@@ -0,0 +1,104 @@
#if !BESTHTTP_DISABLE_SOCKETIO
using System.Collections.Generic;
namespace BestHTTP.SocketIO.Transports
{
public enum TransportTypes
{
Polling,
#if !BESTHTTP_DISABLE_WEBSOCKET
WebSocket
#endif
}
/// <summary>
/// Possible states of an ITransport implementation.
/// </summary>
public enum TransportStates : int
{
/// <summary>
/// The transport is connecting to the server.
/// </summary>
Connecting = 0,
/// <summary>
/// The transport is connected, and started the opening process.
/// </summary>
Opening = 1,
/// <summary>
/// The transport is open, can send and receive packets.
/// </summary>
Open = 2,
/// <summary>
/// The transport is closed.
/// </summary>
Closed = 3,
/// <summary>
/// The transport is paused.
/// </summary>
Paused = 4
}
/// <summary>
/// An interface that a Socket.IO transport must implement.
/// </summary>
public interface ITransport
{
/// <summary>
/// Type of this transport.
/// </summary>
TransportTypes Type { get; }
/// <summary>
/// Current state of the transport
/// </summary>
TransportStates State { get; }
/// <summary>
/// SocketManager instance that this transport is bound to.
/// </summary>
SocketManager Manager { get; }
/// <summary>
/// True if the transport is busy with sending messages.
/// </summary>
bool IsRequestInProgress { get; }
/// <summary>
/// True if the transport is busy with a poll request.
/// </summary>
bool IsPollingInProgress { get; }
/// <summary>
/// Start open/upgrade the transport.
/// </summary>
void Open();
/// <summary>
/// Do a poll for available messages on the server.
/// </summary>
void Poll();
/// <summary>
/// Send a single packet to the server.
/// </summary>
void Send(Packet packet);
/// <summary>
/// Send a list of packets to the server.
/// </summary>
void Send(List<Packet> packets);
/// <summary>
/// Close this transport.
/// </summary>
void Close();
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c11f8a03f5726420eb112813c68aa342
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,415 @@
#if !BESTHTTP_DISABLE_SOCKETIO
using System;
using System.Text;
namespace BestHTTP.SocketIO.Transports
{
internal sealed class PollingTransport : ITransport
{
#region Public (ITransport) Properties
public TransportTypes Type { get { return TransportTypes.Polling; } }
public TransportStates State { get; private set; }
public SocketManager Manager { get; private set; }
public bool IsRequestInProgress { get { return LastRequest != null; } }
public bool IsPollingInProgress { get { return PollRequest != null; } }
#endregion
#region Private Fields
/// <summary>
/// The last POST request we sent to the server.
/// </summary>
private HTTPRequest LastRequest;
/// <summary>
/// Last GET request we sent to the server.
/// </summary>
private HTTPRequest PollRequest;
/// <summary>
/// The last packet with expected binary attachments
/// </summary>
private Packet PacketWithAttachment;
#endregion
private enum PayloadTypes : byte
{
Text,
Binary
}
public PollingTransport(SocketManager manager)
{
Manager = manager;
}
public void Open()
{
string format = "{0}?EIO={1}&transport=polling&t={2}-{3}{5}";
if (Manager.Handshake != null)
format += "&sid={4}";
bool sendAdditionalQueryParams = !Manager.Options.QueryParamsOnlyForHandshake || (Manager.Options.QueryParamsOnlyForHandshake && Manager.Handshake == null);
HTTPRequest request = new HTTPRequest(new Uri(string.Format(format,
Manager.Uri.ToString(),
SocketManager.MinProtocolVersion,
Manager.Timestamp.ToString(),
Manager.RequestCounter++.ToString(),
Manager.Handshake != null ? Manager.Handshake.Sid : string.Empty,
sendAdditionalQueryParams ? Manager.Options.BuildQueryParams() : string.Empty)),
OnRequestFinished);
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
// Don't even try to cache it
request.DisableCache = true;
#endif
request.DisableRetry = true;
request.Send();
State = TransportStates.Opening;
}
/// <summary>
/// Closes the transport and cleans up resources.
/// </summary>
public void Close()
{
if (State == TransportStates.Closed)
return;
State = TransportStates.Closed;
/*
if (LastRequest != null)
LastRequest.Abort();
if (PollRequest != null)
PollRequest.Abort();*/
}
#region Packet Sending Implementation
private System.Collections.Generic.List<Packet> lonelyPacketList = new System.Collections.Generic.List<Packet>(1);
public void Send(Packet packet)
{
try
{
lonelyPacketList.Add(packet);
Send(lonelyPacketList);
}
finally
{
lonelyPacketList.Clear();
}
}
public void Send(System.Collections.Generic.List<Packet> packets)
{
if (State != TransportStates.Open)
throw new Exception("Transport is not in Open state!");
if (IsRequestInProgress)
throw new Exception("Sending packets are still in progress!");
byte[] buffer = null;
try
{
buffer = packets[0].EncodeBinary();
for (int i = 1; i < packets.Count; ++i)
{
byte[] tmpBuffer = packets[i].EncodeBinary();
Array.Resize(ref buffer, buffer.Length + tmpBuffer.Length);
Array.Copy(tmpBuffer, 0, buffer, buffer.Length - tmpBuffer.Length, tmpBuffer.Length);
}
packets.Clear();
}
catch (Exception ex)
{
(Manager as IManager).EmitError(SocketIOErrors.Internal, ex.Message + " " + ex.StackTrace);
return;
}
LastRequest = new HTTPRequest(new Uri(string.Format("{0}?EIO={1}&transport=polling&t={2}-{3}&sid={4}{5}",
Manager.Uri.ToString(),
SocketManager.MinProtocolVersion,
Manager.Timestamp.ToString(),
Manager.RequestCounter++.ToString(),
Manager.Handshake.Sid,
!Manager.Options.QueryParamsOnlyForHandshake ? Manager.Options.BuildQueryParams() : string.Empty)),
HTTPMethods.Post,
OnRequestFinished);
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
// Don't even try to cache it
LastRequest.DisableCache = true;
#endif
LastRequest.SetHeader("Content-Type", "application/octet-stream");
LastRequest.RawData = buffer;
LastRequest.Send();
}
private void OnRequestFinished(HTTPRequest req, HTTPResponse resp)
{
// Clear out the LastRequest variable, so we can start sending out new packets
LastRequest = null;
if (State == TransportStates.Closed)
return;
string errorString = null;
switch (req.State)
{
// The request finished without any problem.
case HTTPRequestStates.Finished:
if (HTTPManager.Logger.Level <= BestHTTP.Logger.Loglevels.All)
HTTPManager.Logger.Verbose("PollingTransport", "OnRequestFinished: " + resp.DataAsText);
if (resp.IsSuccess)
{
// When we are sending data, the response is an 'ok' string
if (req.MethodType != HTTPMethods.Post)
ParseResponse(resp);
}
else
errorString = string.Format("Polling - Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2} Uri: {3}",
resp.StatusCode,
resp.Message,
resp.DataAsText,
req.CurrentUri);
break;
// The request finished with an unexpected error. The request's Exception property may contain more info about the error.
case HTTPRequestStates.Error:
errorString = (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
break;
// The request aborted, initiated by the user.
case HTTPRequestStates.Aborted:
errorString = string.Format("Polling - Request({0}) Aborted!", req.CurrentUri);
break;
// Connecting to the server is timed out.
case HTTPRequestStates.ConnectionTimedOut:
errorString = string.Format("Polling - Connection Timed Out! Uri: {0}", req.CurrentUri);
break;
// The request didn't finished in the given time.
case HTTPRequestStates.TimedOut:
errorString = string.Format("Polling - Processing the request({0}) Timed Out!", req.CurrentUri);
break;
}
if (!string.IsNullOrEmpty(errorString))
(Manager as IManager).OnTransportError(this, errorString);
}
#endregion
#region Polling Implementation
public void Poll()
{
if (PollRequest != null || State == TransportStates.Paused)
return;
PollRequest = new HTTPRequest(new Uri(string.Format("{0}?EIO={1}&transport=polling&t={2}-{3}&sid={4}{5}",
Manager.Uri.ToString(),
SocketManager.MinProtocolVersion,
Manager.Timestamp.ToString(),
Manager.RequestCounter++.ToString(),
Manager.Handshake.Sid,
!Manager.Options.QueryParamsOnlyForHandshake ? Manager.Options.BuildQueryParams() : string.Empty)),
HTTPMethods.Get,
OnPollRequestFinished);
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
// Don't even try to cache it
PollRequest.DisableCache = true;
#endif
PollRequest.DisableRetry = true;
PollRequest.Send();
}
private void OnPollRequestFinished(HTTPRequest req, HTTPResponse resp)
{
// Clear the PollRequest variable, so we can start a new poll.
PollRequest = null;
if (State == TransportStates.Closed)
return;
string errorString = null;
switch (req.State)
{
// The request finished without any problem.
case HTTPRequestStates.Finished:
if (HTTPManager.Logger.Level <= BestHTTP.Logger.Loglevels.All)
HTTPManager.Logger.Verbose("PollingTransport", "OnPollRequestFinished: " + resp.DataAsText);
if (resp.IsSuccess)
ParseResponse(resp);
else
errorString = string.Format("Polling - Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2} Uri: {3}",
resp.StatusCode,
resp.Message,
resp.DataAsText,
req.CurrentUri);
break;
// The request finished with an unexpected error. The request's Exception property may contain more info about the error.
case HTTPRequestStates.Error:
errorString = req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception";
break;
// The request aborted, initiated by the user.
case HTTPRequestStates.Aborted:
errorString = string.Format("Polling - Request({0}) Aborted!", req.CurrentUri);
break;
// Connecting to the server is timed out.
case HTTPRequestStates.ConnectionTimedOut:
errorString = string.Format("Polling - Connection Timed Out! Uri: {0}", req.CurrentUri);
break;
// The request didn't finished in the given time.
case HTTPRequestStates.TimedOut:
errorString = string.Format("Polling - Processing the request({0}) Timed Out!", req.CurrentUri);
break;
}
if (!string.IsNullOrEmpty(errorString))
(Manager as IManager).OnTransportError(this, errorString);
}
#endregion
#region Packet Parsing and Handling
/// <summary>
/// Preprocessing and sending out packets to the manager.
/// </summary>
private void OnPacket(Packet packet)
{
if (packet.AttachmentCount != 0 && !packet.HasAllAttachment)
{
PacketWithAttachment = packet;
return;
}
switch (packet.TransportEvent)
{
case TransportEventTypes.Open:
if (this.State != TransportStates.Opening)
HTTPManager.Logger.Warning("PollingTransport", "Received 'Open' packet while state is '" + State.ToString() + "'");
else
State = TransportStates.Open;
goto default;
default:
(Manager as IManager).OnPacket(packet);
break;
}
}
/// <summary>
/// Will parse the response, and send out the parsed packets.
/// </summary>
private void ParseResponse(HTTPResponse resp)
{
try
{
if (resp != null && resp.Data != null && resp.Data.Length >= 1)
{
int idx = 0;
while (idx < resp.Data.Length)
{
PayloadTypes type = (PayloadTypes)resp.Data[idx++];
int length = 0;
byte num = resp.Data[idx++];
while (num != 0xFF)
{
length = (length * 10) + num;
num = resp.Data[idx++];
}
Packet packet = null;
switch(type)
{
case PayloadTypes.Text:
packet = new Packet(Encoding.UTF8.GetString(resp.Data, idx, length));
break;
case PayloadTypes.Binary:
if (PacketWithAttachment != null)
{
// First byte is the packet type. We can skip it, so we advance our idx and we also have
// to decrease length
idx++;
length--;
byte[] buffer = new byte[length];
Array.Copy(resp.Data, idx, buffer, 0, length);
PacketWithAttachment.AddAttachmentFromServer(buffer, true);
if (PacketWithAttachment.HasAllAttachment)
{
packet = PacketWithAttachment;
PacketWithAttachment = null;
}
}
break;
} // switch
if (packet != null)
{
try
{
OnPacket(packet);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("PollingTransport", "ParseResponse - OnPacket", ex);
(Manager as IManager).EmitError(SocketIOErrors.Internal, ex.Message + " " + ex.StackTrace);
}
}
idx += length;
}// while
}
}
catch (Exception ex)
{
(Manager as IManager).EmitError(SocketIOErrors.Internal, ex.Message + " " + ex.StackTrace);
HTTPManager.Logger.Exception("PollingTransport", "ParseResponse", ex);
}
}
#endregion
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 32a1aec6224654cf984fcacbae02b064
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,353 @@
#if !BESTHTTP_DISABLE_SOCKETIO
#if !BESTHTTP_DISABLE_WEBSOCKET
using System;
using System.Collections.Generic;
namespace BestHTTP.SocketIO.Transports
{
using BestHTTP.WebSocket;
using Extensions;
/// <summary>
/// A transport implementation that can communicate with a SocketIO server.
/// </summary>
internal sealed class WebSocketTransport : ITransport
{
public TransportTypes Type { get { return TransportTypes.WebSocket; } }
public TransportStates State { get; private set; }
public SocketManager Manager { get; private set; }
public bool IsRequestInProgress { get { return false; } }
public bool IsPollingInProgress { get { return false; } }
public WebSocket Implementation { get; private set; }
private Packet PacketWithAttachment;
private byte[] Buffer;
public WebSocketTransport(SocketManager manager)
{
State = TransportStates.Closed;
Manager = manager;
}
#region Some ITransport Implementation
public void Open()
{
if (State != TransportStates.Closed)
return;
Uri uri = null;
string baseUrl = new UriBuilder(HTTPProtocolFactory.IsSecureProtocol(Manager.Uri) ? "wss" : "ws",
Manager.Uri.Host,
Manager.Uri.Port,
Manager.Uri.GetRequestPathAndQueryURL()).Uri.ToString();
string format = "{0}?EIO={1}&transport=websocket{3}";
if (Manager.Handshake != null)
format += "&sid={2}";
bool sendAdditionalQueryParams = !Manager.Options.QueryParamsOnlyForHandshake || (Manager.Options.QueryParamsOnlyForHandshake && Manager.Handshake == null);
uri = new Uri(string.Format(format,
baseUrl,
SocketManager.MinProtocolVersion,
Manager.Handshake != null ? Manager.Handshake.Sid : string.Empty,
sendAdditionalQueryParams ? Manager.Options.BuildQueryParams() : string.Empty));
Implementation = new WebSocket(uri);
Implementation.OnOpen = OnOpen;
Implementation.OnMessage = OnMessage;
Implementation.OnBinary = OnBinary;
Implementation.OnError = OnError;
Implementation.OnClosed = OnClosed;
Implementation.Open();
State = TransportStates.Connecting;
}
/// <summary>
/// Closes the transport and cleans up resources.
/// </summary>
public void Close()
{
if (State == TransportStates.Closed)
return;
State = TransportStates.Closed;
if (Implementation != null)
Implementation.Close();
else
HTTPManager.Logger.Warning("WebSocketTransport", "Close - WebSocket Implementation already null!");
Implementation = null;
}
/// <summary>
/// Polling implementation. With WebSocket it's just a skeleton.
/// </summary>
public void Poll()
{
}
#endregion
#region WebSocket Events
/// <summary>
/// WebSocket implementation OnOpen event handler.
/// </summary>
private void OnOpen(WebSocket ws)
{
if (ws != Implementation)
return;
HTTPManager.Logger.Information("WebSocketTransport", "OnOpen");
State = TransportStates.Opening;
// Send a Probe packet to test the transport. If we receive back a pong with the same payload we can upgrade
if (Manager.UpgradingTransport == this)
Send(new Packet(TransportEventTypes.Ping, SocketIOEventTypes.Unknown, "/", "probe"));
}
/// <summary>
/// WebSocket implementation OnMessage event handler.
/// </summary>
private void OnMessage(WebSocket ws, string message)
{
if (ws != Implementation)
return;
if (HTTPManager.Logger.Level <= BestHTTP.Logger.Loglevels.All)
HTTPManager.Logger.Verbose("WebSocketTransport", "OnMessage: " + message);
try
{
Packet packet = new Packet(message);
if (packet.AttachmentCount == 0)
OnPacket(packet);
else
PacketWithAttachment = packet;
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("WebSocketTransport", "OnMessage", ex);
}
}
/// <summary>
/// WebSocket implementation OnBinary event handler.
/// </summary>
private void OnBinary(WebSocket ws, byte[] data)
{
if (ws != Implementation)
return;
if (HTTPManager.Logger.Level <= BestHTTP.Logger.Loglevels.All)
HTTPManager.Logger.Verbose("WebSocketTransport", "OnBinary");
if (PacketWithAttachment != null)
{
PacketWithAttachment.AddAttachmentFromServer(data, false);
if (PacketWithAttachment.HasAllAttachment)
{
try
{
OnPacket(PacketWithAttachment);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("WebSocketTransport", "OnBinary", ex);
}
finally
{
PacketWithAttachment = null;
}
}
}
else
{
// TODO: we received an unwanted binary message?
}
}
/// <summary>
/// WebSocket implementation OnError event handler.
/// </summary>
private void OnError(WebSocket ws, Exception ex)
{
if (ws != Implementation)
return;
string errorStr = string.Empty;
if (ex != null)
errorStr = (ex.Message + " " + ex.StackTrace);
else
{
#if !UNITY_WEBGL || UNITY_EDITOR
switch (ws.InternalRequest.State)
{
// The request finished without any problem.
case HTTPRequestStates.Finished:
if (ws.InternalRequest.Response.IsSuccess || ws.InternalRequest.Response.StatusCode == 101)
errorStr = string.Format("Request finished. Status Code: {0} Message: {1}", ws.InternalRequest.Response.StatusCode.ToString(), ws.InternalRequest.Response.Message);
else
errorStr = string.Format("Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
ws.InternalRequest.Response.StatusCode,
ws.InternalRequest.Response.Message,
ws.InternalRequest.Response.DataAsText);
break;
// The request finished with an unexpected error. The request's Exception property may contain more info about the error.
case HTTPRequestStates.Error:
errorStr = "Request Finished with Error! : " + ws.InternalRequest.Exception != null ? (ws.InternalRequest.Exception.Message + " " + ws.InternalRequest.Exception.StackTrace) : string.Empty;
break;
// The request aborted, initiated by the user.
case HTTPRequestStates.Aborted:
errorStr = "Request Aborted!";
break;
// Connecting to the server is timed out.
case HTTPRequestStates.ConnectionTimedOut:
errorStr = "Connection Timed Out!";
break;
// The request didn't finished in the given time.
case HTTPRequestStates.TimedOut:
errorStr = "Processing the request Timed Out!";
break;
}
#endif
}
if (Manager.UpgradingTransport != this)
(Manager as IManager).OnTransportError(this, errorStr);
else
Manager.UpgradingTransport = null;
}
/// <summary>
/// WebSocket implementation OnClosed event handler.
/// </summary>
private void OnClosed(WebSocket ws, ushort code, string message)
{
if (ws != Implementation)
return;
HTTPManager.Logger.Information("WebSocketTransport", "OnClosed");
Close();
if (Manager.UpgradingTransport != this)
(Manager as IManager).TryToReconnect();
else
Manager.UpgradingTransport = null;
}
#endregion
#region Packet Sending Implementation
/// <summary>
/// A WebSocket implementation of the packet sending.
/// </summary>
public void Send(Packet packet)
{
if (State == TransportStates.Closed ||
State == TransportStates.Paused)
return;
string encoded = packet.Encode();
if (HTTPManager.Logger.Level <= BestHTTP.Logger.Loglevels.All)
HTTPManager.Logger.Verbose("WebSocketTransport", "Send: " + encoded);
if (packet.AttachmentCount != 0 || (packet.Attachments != null && packet.Attachments.Count != 0))
{
if (packet.Attachments == null)
throw new ArgumentException("packet.Attachments are null!");
if (packet.AttachmentCount != packet.Attachments.Count)
throw new ArgumentException("packet.AttachmentCount != packet.Attachments.Count. Use the packet.AddAttachment function to add data to a packet!");
}
Implementation.Send(encoded);
if (packet.AttachmentCount != 0)
{
int maxLength = packet.Attachments[0].Length + 1;
for (int cv = 1; cv < packet.Attachments.Count; ++cv)
if ((packet.Attachments[cv].Length + 1) > maxLength)
maxLength = packet.Attachments[cv].Length + 1;
if (Buffer == null || Buffer.Length < maxLength)
Array.Resize(ref Buffer, maxLength);
for (int i = 0; i < packet.AttachmentCount; i++)
{
Buffer[0] = (byte)TransportEventTypes.Message;
Array.Copy(packet.Attachments[i], 0, Buffer, 1, packet.Attachments[i].Length);
Implementation.Send(Buffer, 0, (ulong)packet.Attachments[i].Length + 1UL);
}
}
}
/// <summary>
/// A WebSocket implementation of the packet sending.
/// </summary>
public void Send(List<Packet> packets)
{
for (int i = 0; i < packets.Count; ++i)
Send(packets[i]);
packets.Clear();
}
#endregion
#region Packet Handling
/// <summary>
/// Will only process packets that need to upgrade. All other packets are passed to the Manager.
/// </summary>
private void OnPacket(Packet packet)
{
switch (packet.TransportEvent)
{
case TransportEventTypes.Open:
if (this.State != TransportStates.Opening)
HTTPManager.Logger.Warning("PollingTransport", "Received 'Open' packet while state is '" + State.ToString() + "'");
else
State = TransportStates.Open;
goto default;
case TransportEventTypes.Pong:
// Answer for a Ping Probe.
if (packet.Payload == "probe")
{
State = TransportStates.Open;
(Manager as IManager).OnTransportProbed(this);
}
goto default;
default:
if (Manager.UpgradingTransport != this)
(Manager as IManager).OnPacket(packet);
break;
}
}
#endregion
}
}
#endif
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 642562a6af9424da28f8bc28eeb9ef21
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: