You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Gateway/Mime/HttpWebSocket.cs

105 lines
2.8 KiB
C#

2 years ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
2 years ago
using System.IO;
1 year ago
using System.Net.Sockets;
2 years ago
using System.Text;
using UMC.Net;
1 year ago
namespace UMC.Proxy
2 years ago
{
1 year ago
abstract class WebSocket : UMC.Net.MimeRequest, IDisposable
{
public override bool IsWebSocket => true;
public abstract void Dispose();
2 years ago
}
1 year ago
class HttpWebSocket : WebSocket
{
1 year ago
byte[] buffer = System.Buffers.ArrayPool<byte>.Shared.Rent(0x600);
1 year ago
Socket socket;
public HttpWebSocket(HttpMime mime, Socket stream)
{
this.mime = mime;
this.socket = stream;
SocketAsyncEventArgs eventArgs = new SocketAsyncEventArgs();
eventArgs.SetBuffer(buffer);
eventArgs.Completed += Http;
if (!this.socket.ReceiveAsync(eventArgs))
{
ProcessReceive(eventArgs);
}
}
HttpMime mime;
private void Http(object sender, SocketAsyncEventArgs e)
{
switch (e.LastOperation)
{
case SocketAsyncOperation.Receive:
ProcessReceive(e);
break;
}
}
private void ProcessReceive(SocketAsyncEventArgs e)
{
if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
{
try
{
this.mime.Write(buffer, e.Offset, e.BytesTransferred);
10 months ago
while (!socket.ReceiveAsync(e))
1 year ago
{
10 months ago
if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
{
this.mime.Write(buffer, e.Offset, e.BytesTransferred);
}
else
{
this.Dispose();
break;
}
1 year ago
}
}
catch
{
this.Dispose();
}
}
else
{
this.Dispose();
}
}
public override void Receive(byte[] buffer, int offset, int size)
{
socket.Send(buffer, offset, size, SocketFlags.None);
}
protected override void Header(byte[] data, int offset, int size)
{
}
public override void Dispose()
{
1 year ago
this.mime.Dispose();
1 year ago
try
{
socket.Shutdown(SocketShutdown.Both);
}
catch
{
}
socket.Close();
1 year ago
if (buffer != null)
System.Buffers.ArrayPool<byte>.Shared.Return(buffer);
1 year ago
buffer = null;
}
}
2 years ago
}