mirror of
https://github.com/esiur/esiur-dotnet.git
synced 2025-06-27 05:23:13 +00:00
Rename
This commit is contained in:
74
Esiur/Net/Sockets/ISocket.cs
Normal file
74
Esiur/Net/Sockets/ISocket.cs
Normal file
@ -0,0 +1,74 @@
|
||||
/*
|
||||
|
||||
Copyright (c) 2017 Ahmed Kh. Zamil
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Net;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using Esiur.Data;
|
||||
using Esiur.Misc;
|
||||
using System.Collections.Concurrent;
|
||||
using Esiur.Resource;
|
||||
using Esiur.Core;
|
||||
|
||||
namespace Esiur.Net.Sockets
|
||||
{
|
||||
//public delegate void ISocketReceiveEvent(NetworkBuffer buffer);
|
||||
//public delegate void ISocketConnectEvent();
|
||||
//public delegate void ISocketCloseEvent();
|
||||
|
||||
public interface ISocket : IDestructible
|
||||
{
|
||||
SocketState State { get; }
|
||||
|
||||
//event ISocketReceiveEvent OnReceive;
|
||||
//event ISocketConnectEvent OnConnect;
|
||||
//event ISocketCloseEvent OnClose;
|
||||
|
||||
INetworkReceiver<ISocket> Receiver { get; set; }
|
||||
|
||||
AsyncReply<bool> SendAsync(byte[] message, int offset, int length);
|
||||
|
||||
void Send(byte[] message);
|
||||
void Send(byte[] message, int offset, int length);
|
||||
void Close();
|
||||
AsyncReply<bool> Connect(string hostname, ushort port);
|
||||
bool Begin();
|
||||
AsyncReply<bool> BeginAsync();
|
||||
//ISocket Accept();
|
||||
AsyncReply<ISocket> AcceptAsync();
|
||||
ISocket Accept();
|
||||
|
||||
IPEndPoint RemoteEndPoint { get; }
|
||||
IPEndPoint LocalEndPoint { get; }
|
||||
|
||||
void Hold();
|
||||
|
||||
void Unhold();
|
||||
}
|
||||
}
|
555
Esiur/Net/Sockets/SSLSocket.cs
Normal file
555
Esiur/Net/Sockets/SSLSocket.cs
Normal file
@ -0,0 +1,555 @@
|
||||
/*
|
||||
|
||||
Copyright (c) 2017 Ahmed Kh. Zamil
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Net.Sockets;
|
||||
using System.Net;
|
||||
using Esiur.Misc;
|
||||
using Esiur.Core;
|
||||
using System.Threading;
|
||||
using System.Net.Security;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Esiur.Resource;
|
||||
using System.Threading.Tasks;
|
||||
using Esiur.Data;
|
||||
|
||||
namespace Esiur.Net.Sockets
|
||||
{
|
||||
public class SSLSocket : ISocket
|
||||
{
|
||||
|
||||
public INetworkReceiver<ISocket> Receiver { get; set; }
|
||||
|
||||
Socket sock;
|
||||
byte[] receiveBuffer;
|
||||
|
||||
bool held;
|
||||
|
||||
//ArraySegment<byte> receiveBufferSegment;
|
||||
|
||||
NetworkBuffer receiveNetworkBuffer = new NetworkBuffer();
|
||||
|
||||
readonly object sendLock = new object();
|
||||
|
||||
Queue<KeyValuePair<AsyncReply<bool>, byte[]>> sendBufferQueue = new Queue<KeyValuePair<AsyncReply<bool>, byte[]>>();// Queue<byte[]>();
|
||||
|
||||
bool asyncSending;
|
||||
bool began = false;
|
||||
|
||||
SocketState state = SocketState.Initial;
|
||||
|
||||
//public event ISocketReceiveEvent OnReceive;
|
||||
//public event ISocketConnectEvent OnConnect;
|
||||
//public event ISocketCloseEvent OnClose;
|
||||
public event DestroyedEvent OnDestroy;
|
||||
|
||||
|
||||
SslStream ssl;
|
||||
X509Certificate2 cert;
|
||||
bool server;
|
||||
string hostname;
|
||||
|
||||
|
||||
public async AsyncReply<bool> Connect(string hostname, ushort port)
|
||||
{
|
||||
var rt = new AsyncReply<bool>();
|
||||
|
||||
this.hostname = hostname;
|
||||
this.server = false;
|
||||
|
||||
state = SocketState.Connecting;
|
||||
await sock.ConnectAsync(hostname, port);
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
await BeginAsync();
|
||||
state = SocketState.Established;
|
||||
//OnConnect?.Invoke();
|
||||
Receiver?.NetworkConnect(this);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
state = SocketState.Closed;// .Terminated;
|
||||
Close();
|
||||
Global.Log(ex);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//private void DataSent(Task task)
|
||||
//{
|
||||
// try
|
||||
// {
|
||||
|
||||
// if (sendBufferQueue.Count > 0)
|
||||
// {
|
||||
// byte[] data = sendBufferQueue.Dequeue();
|
||||
// lock (sendLock)
|
||||
// ssl.WriteAsync(data, 0, data.Length).ContinueWith(DataSent);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// asyncSending = false;
|
||||
// }
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// if (state != SocketState.Closed && !sock.Connected)
|
||||
// {
|
||||
// state = SocketState.Terminated;
|
||||
// Close();
|
||||
// }
|
||||
|
||||
// asyncSending = false;
|
||||
|
||||
// Global.Log("SSLSocket", LogType.Error, ex.ToString());
|
||||
// }
|
||||
//}
|
||||
|
||||
|
||||
private void SendCallback(IAsyncResult ar)
|
||||
{
|
||||
if (ar != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
ssl.EndWrite(ar);
|
||||
|
||||
if (ar.AsyncState != null)
|
||||
((AsyncReply<bool>)ar.AsyncState).Trigger(true);
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (state != SocketState.Closed && !sock.Connected)
|
||||
{
|
||||
//state = SocketState.Closed;//.Terminated;
|
||||
Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lock (sendLock)
|
||||
{
|
||||
|
||||
if (sendBufferQueue.Count > 0)
|
||||
{
|
||||
var kv = sendBufferQueue.Dequeue();
|
||||
|
||||
try
|
||||
{
|
||||
ssl.BeginWrite(kv.Value, 0, kv.Value.Length, SendCallback, kv.Key);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
asyncSending = false;
|
||||
try
|
||||
{
|
||||
if (kv.Key != null)
|
||||
kv.Key.Trigger(false);
|
||||
|
||||
if (state != SocketState.Closed && !sock.Connected)
|
||||
{
|
||||
//state = SocketState.Terminated;
|
||||
Close();
|
||||
}
|
||||
}
|
||||
catch (Exception ex2)
|
||||
{
|
||||
//state = SocketState.Closed;// .Terminated;
|
||||
Close();
|
||||
}
|
||||
|
||||
//Global.Log("TCPSocket", LogType.Error, ex.ToString());
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
asyncSending = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public IPEndPoint LocalEndPoint
|
||||
{
|
||||
get { return (IPEndPoint)sock.LocalEndPoint; }
|
||||
}
|
||||
|
||||
public SSLSocket()
|
||||
{
|
||||
sock = new Socket(AddressFamily.InterNetwork,
|
||||
SocketType.Stream,
|
||||
ProtocolType.Tcp);
|
||||
receiveBuffer = new byte[sock.ReceiveBufferSize];
|
||||
}
|
||||
|
||||
public SSLSocket(IPEndPoint localEndPoint, X509Certificate2 certificate)
|
||||
{
|
||||
// create the socket
|
||||
sock = new Socket(AddressFamily.InterNetwork,
|
||||
SocketType.Stream,
|
||||
ProtocolType.Tcp);
|
||||
|
||||
state = SocketState.Listening;
|
||||
|
||||
// bind
|
||||
sock.Bind(localEndPoint);
|
||||
|
||||
// start listening
|
||||
sock.Listen(UInt16.MaxValue);
|
||||
|
||||
cert = certificate;
|
||||
}
|
||||
|
||||
public IPEndPoint RemoteEndPoint
|
||||
{
|
||||
get { return (IPEndPoint)sock.RemoteEndPoint; }
|
||||
}
|
||||
|
||||
public SocketState State
|
||||
{
|
||||
get
|
||||
{
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public SSLSocket(Socket socket, X509Certificate2 certificate, bool authenticateAsServer)
|
||||
{
|
||||
cert = certificate;
|
||||
sock = socket;
|
||||
receiveBuffer = new byte[sock.ReceiveBufferSize];
|
||||
|
||||
ssl = new SslStream(new NetworkStream(sock));
|
||||
|
||||
server = authenticateAsServer;
|
||||
|
||||
if (socket.Connected)
|
||||
state = SocketState.Established;
|
||||
}
|
||||
|
||||
|
||||
public void Close()
|
||||
{
|
||||
if (state != SocketState.Closed)// && state != SocketState.Terminated)
|
||||
{
|
||||
state = SocketState.Closed;
|
||||
|
||||
if (sock.Connected)
|
||||
{
|
||||
try
|
||||
{
|
||||
sock.Shutdown(SocketShutdown.Both);
|
||||
}
|
||||
catch
|
||||
{
|
||||
//state = SocketState.Terminated;
|
||||
}
|
||||
}
|
||||
|
||||
Receiver?.NetworkClose(this);
|
||||
//OnClose?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void Send(byte[] message)
|
||||
{
|
||||
Send(message, 0, message.Length);
|
||||
}
|
||||
|
||||
|
||||
public void Send(byte[] message, int offset, int size)
|
||||
{
|
||||
|
||||
|
||||
var msg = message.Clip((uint)offset, (uint)size);
|
||||
|
||||
lock (sendLock)
|
||||
{
|
||||
|
||||
if (!sock.Connected)
|
||||
return;
|
||||
|
||||
if (asyncSending || held)
|
||||
{
|
||||
sendBufferQueue.Enqueue(new KeyValuePair<AsyncReply<bool>, byte[]>(null, msg));// message.Clip((uint)offset, (uint)size));
|
||||
}
|
||||
else
|
||||
{
|
||||
asyncSending = true;
|
||||
try
|
||||
{
|
||||
ssl.BeginWrite(msg, 0, msg.Length, SendCallback, null);
|
||||
}
|
||||
catch
|
||||
{
|
||||
asyncSending = false;
|
||||
//state = SocketState.Terminated;
|
||||
Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//public void Send(byte[] message)
|
||||
//{
|
||||
// Send(message, 0, message.Length);
|
||||
//}
|
||||
|
||||
//public void Send(byte[] message, int offset, int size)
|
||||
//{
|
||||
// lock (sendLock)
|
||||
// {
|
||||
// if (asyncSending)
|
||||
// {
|
||||
// sendBufferQueue.Enqueue(message.Clip((uint)offset, (uint)size));
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// asyncSending = true;
|
||||
// ssl.WriteAsync(message, offset, size).ContinueWith(DataSent);
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
|
||||
|
||||
|
||||
//private void DataReceived(Task<int> task)
|
||||
//{
|
||||
// try
|
||||
// {
|
||||
// if (state == SocketState.Closed || state == SocketState.Terminated)
|
||||
// return;
|
||||
|
||||
// if (task.Result <= 0)
|
||||
// {
|
||||
// Close();
|
||||
// return;
|
||||
// }
|
||||
|
||||
// receiveNetworkBuffer.Write(receiveBuffer, 0, (uint)task.Result);
|
||||
// OnReceive?.Invoke(receiveNetworkBuffer);
|
||||
// if (state == SocketState.Established)
|
||||
// ssl.ReadAsync(receiveBuffer, 0, receiveBuffer.Length).ContinueWith(DataReceived);
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// if (state != SocketState.Closed && !sock.Connected)
|
||||
// {
|
||||
// state = SocketState.Terminated;
|
||||
// Close();
|
||||
// }
|
||||
|
||||
// Global.Log("SSLSocket", LogType.Error, ex.ToString());
|
||||
// }
|
||||
//}
|
||||
|
||||
|
||||
public bool Begin()
|
||||
{
|
||||
if (began)
|
||||
return false;
|
||||
|
||||
began = true;
|
||||
|
||||
if (server)
|
||||
ssl.AuthenticateAsServer(cert);
|
||||
else
|
||||
ssl.AuthenticateAsClient(hostname);
|
||||
|
||||
if (state == SocketState.Established)
|
||||
{
|
||||
ssl.BeginRead(receiveBuffer, 0, receiveBuffer.Length, ReceiveCallback, this);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
public async AsyncReply<bool> BeginAsync()
|
||||
{
|
||||
if (began)
|
||||
return false;
|
||||
|
||||
began = true;
|
||||
|
||||
if (server)
|
||||
await ssl.AuthenticateAsServerAsync(cert);
|
||||
else
|
||||
await ssl.AuthenticateAsClientAsync(hostname);
|
||||
|
||||
if (state == SocketState.Established)
|
||||
{
|
||||
ssl.BeginRead(receiveBuffer, 0, receiveBuffer.Length, ReceiveCallback, this);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
private void ReceiveCallback(IAsyncResult results)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (state != SocketState.Established)
|
||||
return;
|
||||
|
||||
var bytesReceived = ssl.EndRead(results);
|
||||
|
||||
if (bytesReceived <= 0)
|
||||
{
|
||||
Close();
|
||||
return;
|
||||
}
|
||||
|
||||
receiveNetworkBuffer.Write(receiveBuffer, 0, (uint)bytesReceived);
|
||||
|
||||
//OnReceive?.Invoke(receiveNetworkBuffer);
|
||||
|
||||
Receiver?.NetworkReceive(this, receiveNetworkBuffer);
|
||||
|
||||
ssl.BeginRead(receiveBuffer, 0, receiveBuffer.Length, ReceiveCallback, this);
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (state != SocketState.Closed && !sock.Connected)
|
||||
{
|
||||
//state = SocketState.Terminated;
|
||||
Close();
|
||||
}
|
||||
|
||||
//Global.Log("SSLSocket", LogType.Error, ex.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
public bool Trigger(ResourceTrigger trigger)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Destroy()
|
||||
{
|
||||
Close();
|
||||
Receiver = null;
|
||||
receiveNetworkBuffer = null;
|
||||
OnDestroy?.Invoke(this);
|
||||
OnDestroy = null;
|
||||
}
|
||||
|
||||
public async AsyncReply<ISocket> AcceptAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var s = await sock.AcceptAsync();
|
||||
return new SSLSocket(s, cert, true);
|
||||
}
|
||||
catch
|
||||
{
|
||||
state = SocketState.Closed;// Terminated;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void Hold()
|
||||
{
|
||||
held = true;
|
||||
}
|
||||
|
||||
public void Unhold()
|
||||
{
|
||||
try
|
||||
{
|
||||
SendCallback(null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Global.Log(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
held = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public AsyncReply<bool> SendAsync(byte[] message, int offset, int length)
|
||||
{
|
||||
|
||||
var msg = message.Clip((uint)offset, (uint)length);
|
||||
|
||||
lock (sendLock)
|
||||
{
|
||||
if (!sock.Connected)
|
||||
return new AsyncReply<bool>(false);
|
||||
|
||||
var rt = new AsyncReply<bool>();
|
||||
|
||||
if (asyncSending || held)
|
||||
{
|
||||
sendBufferQueue.Enqueue(new KeyValuePair<AsyncReply<bool>, byte[]>(rt, msg));
|
||||
}
|
||||
else
|
||||
{
|
||||
asyncSending = true;
|
||||
try
|
||||
{
|
||||
ssl.BeginWrite(msg, 0, msg.Length, SendCallback, rt);// null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
rt.TriggerError(ex);
|
||||
asyncSending = false;
|
||||
//state = SocketState.Terminated;
|
||||
Close();
|
||||
}
|
||||
}
|
||||
|
||||
return rt;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public ISocket Accept()
|
||||
{
|
||||
try
|
||||
{
|
||||
return new SSLSocket(sock.Accept(), cert, true);
|
||||
}
|
||||
catch
|
||||
{
|
||||
state = SocketState.Closed;// .Terminated;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
42
Esiur/Net/Sockets/SocketState.cs
Normal file
42
Esiur/Net/Sockets/SocketState.cs
Normal file
@ -0,0 +1,42 @@
|
||||
/*
|
||||
|
||||
Copyright (c) 2017 Ahmed Kh. Zamil
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Esiur.Net.Sockets
|
||||
{
|
||||
public enum SocketState
|
||||
{
|
||||
Initial,
|
||||
Listening,
|
||||
Connecting,
|
||||
Established,
|
||||
Closed,
|
||||
//Terminated
|
||||
}
|
||||
}
|
659
Esiur/Net/Sockets/TCPSocket.cs
Normal file
659
Esiur/Net/Sockets/TCPSocket.cs
Normal file
@ -0,0 +1,659 @@
|
||||
/*
|
||||
|
||||
Copyright (c) 2017 Ahmed Kh. Zamil
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Net.Sockets;
|
||||
using System.Net;
|
||||
using Esiur.Misc;
|
||||
using Esiur.Core;
|
||||
using System.Threading;
|
||||
using Esiur.Resource;
|
||||
using System.Threading.Tasks;
|
||||
using Esiur.Data;
|
||||
|
||||
namespace Esiur.Net.Sockets
|
||||
{
|
||||
public class TCPSocket : ISocket
|
||||
{
|
||||
public INetworkReceiver<ISocket> Receiver { get; set; }
|
||||
|
||||
Socket sock;
|
||||
byte[] receiveBuffer;
|
||||
|
||||
bool held;
|
||||
|
||||
//ArraySegment<byte> receiveBufferSegment;
|
||||
|
||||
NetworkBuffer receiveNetworkBuffer = new NetworkBuffer();
|
||||
|
||||
readonly object sendLock = new object();
|
||||
|
||||
Queue<KeyValuePair<AsyncReply<bool>, byte[]>> sendBufferQueue = new Queue<KeyValuePair<AsyncReply<bool>, byte[]>>();// Queue<byte[]>();
|
||||
|
||||
bool asyncSending;
|
||||
bool began = false;
|
||||
|
||||
|
||||
SocketState state = SocketState.Initial;
|
||||
|
||||
//public event ISocketReceiveEvent OnReceive;
|
||||
//public event ISocketConnectEvent OnConnect;
|
||||
//public event ISocketCloseEvent OnClose;
|
||||
public event DestroyedEvent OnDestroy;
|
||||
|
||||
//SocketAsyncEventArgs socketArgs = new SocketAsyncEventArgs();
|
||||
|
||||
private AsyncCallback receiveCallback;
|
||||
private AsyncCallback sendCallback;
|
||||
|
||||
public AsyncReply<bool> BeginAsync()
|
||||
{
|
||||
return new AsyncReply<bool>(Begin());
|
||||
}
|
||||
|
||||
|
||||
private AsyncReply<bool> currentReply = null;
|
||||
|
||||
public bool Begin()
|
||||
{
|
||||
if (began)
|
||||
return false;
|
||||
|
||||
began = true;
|
||||
/*
|
||||
|
||||
socketArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
|
||||
socketArgs.Completed += SocketArgs_Completed;
|
||||
|
||||
if (!sock.ReceiveAsync(socketArgs))
|
||||
SocketArgs_Completed(null, socketArgs);
|
||||
*/
|
||||
receiveCallback = new AsyncCallback(ReceiveCallback);
|
||||
sendCallback = new AsyncCallback(SendCallback);
|
||||
|
||||
sock.BeginReceive(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, receiveCallback, this);
|
||||
//sock.ReceiveAsync(receiveBufferSegment, SocketFlags.None).ContinueWith(DataReceived);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void ReceiveCallback(IAsyncResult ar)
|
||||
{
|
||||
var socket = ar.AsyncState as TCPSocket;
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
if (socket.state != SocketState.Established)
|
||||
return;
|
||||
|
||||
var recCount = socket.sock.EndReceive(ar);
|
||||
|
||||
if (recCount > 0)
|
||||
{
|
||||
socket.receiveNetworkBuffer.Write(socket.receiveBuffer, 0, (uint)recCount);
|
||||
socket.Receiver?.NetworkReceive(socket, socket.receiveNetworkBuffer);
|
||||
|
||||
if (socket.state == SocketState.Established)
|
||||
socket.sock.BeginReceive(socket.receiveBuffer, 0, socket.receiveBuffer.Length, SocketFlags.None, socket.receiveCallback, socket);
|
||||
}
|
||||
else
|
||||
{
|
||||
socket.Close();
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (socket.state != SocketState.Closed && !socket.sock.Connected)
|
||||
{
|
||||
//socket.state = SocketState.Terminated;
|
||||
socket.Close();
|
||||
}
|
||||
|
||||
//Global.Log("TCPSocket", LogType.Error, ex.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public AsyncReply<bool> Connect(string hostname, ushort port)
|
||||
{
|
||||
var rt = new AsyncReply<bool>();
|
||||
|
||||
try
|
||||
{
|
||||
state = SocketState.Connecting;
|
||||
sock.ConnectAsync(hostname, port).ContinueWith((x) =>
|
||||
{
|
||||
|
||||
if (x.IsFaulted)
|
||||
rt.TriggerError(x.Exception);
|
||||
else
|
||||
{
|
||||
|
||||
state = SocketState.Established;
|
||||
//OnConnect?.Invoke();
|
||||
Receiver?.NetworkConnect(this);
|
||||
Begin();
|
||||
rt.Trigger(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
rt.TriggerError(ex);
|
||||
}
|
||||
|
||||
return rt;
|
||||
}
|
||||
|
||||
|
||||
//private void DataReceived(Task<int> task)
|
||||
//{
|
||||
// try
|
||||
// {
|
||||
// // SocketError err;
|
||||
|
||||
// if (state == SocketState.Closed || state == SocketState.Terminated)
|
||||
// return;
|
||||
|
||||
// if (task.Result <= 0)
|
||||
// {
|
||||
// Close();
|
||||
// return;
|
||||
// }
|
||||
|
||||
// receiveNetworkBuffer.Write(receiveBuffer, 0, (uint)task.Result);
|
||||
// //OnReceive?.Invoke(receiveNetworkBuffer);
|
||||
// Receiver?.NetworkReceive(this, receiveNetworkBuffer);
|
||||
// if (state == SocketState.Established)
|
||||
// sock.ReceiveAsync(receiveBufferSegment, SocketFlags.None).ContinueWith(DataReceived);
|
||||
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// if (state != SocketState.Closed && !sock.Connected)
|
||||
// {
|
||||
// state = SocketState.Terminated;
|
||||
// Close();
|
||||
// }
|
||||
|
||||
// Global.Log("TCPSocket", LogType.Error, ex.ToString());
|
||||
// }
|
||||
//}
|
||||
|
||||
//private void SocketArgs_Completed(object sender, SocketAsyncEventArgs e)
|
||||
//{
|
||||
// try
|
||||
// {
|
||||
// if (state != SocketState.Established)
|
||||
// return;
|
||||
|
||||
// if (e.BytesTransferred <= 0)
|
||||
// {
|
||||
// Close();
|
||||
// return;
|
||||
// }
|
||||
// else if (e.SocketError != SocketError.Success)
|
||||
// {
|
||||
// Close();
|
||||
// return;
|
||||
|
||||
// }
|
||||
|
||||
// var recCount = e.BytesTransferred > e.Count ? e.Count : e.BytesTransferred;
|
||||
// receiveNetworkBuffer.Write(receiveBuffer, 0, (uint)recCount);
|
||||
|
||||
// //OnReceive?.Invoke(receiveNetworkBuffer);
|
||||
// Receiver?.NetworkReceive(this, receiveNetworkBuffer);
|
||||
|
||||
// if (state == SocketState.Established)
|
||||
// while (!sock.ReceiveAsync(e))
|
||||
// {
|
||||
// if (e.SocketError != SocketError.Success)
|
||||
// {
|
||||
// Close();
|
||||
// return;
|
||||
// }
|
||||
|
||||
// if (State != SocketState.Established)
|
||||
// return;
|
||||
|
||||
// //if (e.BytesTransferred < 0)
|
||||
// // Console.WriteLine("BytesTransferred is less than zero");
|
||||
|
||||
// if (e.BytesTransferred <= 0)
|
||||
// {
|
||||
// Close();
|
||||
// return;
|
||||
// }
|
||||
// else if (e.SocketError != SocketError.Success)
|
||||
// {
|
||||
// Close();
|
||||
// return;
|
||||
// }
|
||||
|
||||
|
||||
// //if (e.BytesTransferred > 100000)
|
||||
// // Console.WriteLine("BytesTransferred is large " + e.BytesTransferred);
|
||||
|
||||
// recCount = e.BytesTransferred > e.Count ? e.Count : e.BytesTransferred;
|
||||
|
||||
// receiveNetworkBuffer.Write(receiveBuffer, 0, (uint)recCount);
|
||||
|
||||
// //OnReceive?.Invoke(receiveNetworkBuffer);
|
||||
// Receiver?.NetworkReceive(this, receiveNetworkBuffer);
|
||||
// }
|
||||
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// if (state != SocketState.Closed && !sock.Connected)
|
||||
// {
|
||||
// state = SocketState.Terminated;
|
||||
// Close();
|
||||
// }
|
||||
|
||||
// Global.Log("TCPSocket", LogType.Error, ex.ToString());
|
||||
// }
|
||||
//}
|
||||
|
||||
public IPEndPoint LocalEndPoint
|
||||
{
|
||||
get { return (IPEndPoint)sock.LocalEndPoint; }
|
||||
}
|
||||
|
||||
public TCPSocket()
|
||||
{
|
||||
sock = new Socket(AddressFamily.InterNetwork,
|
||||
SocketType.Stream,
|
||||
ProtocolType.Tcp);
|
||||
receiveBuffer = new byte[sock.ReceiveBufferSize];
|
||||
//receiveBufferSegment = new ArraySegment<byte>(receiveBuffer);
|
||||
|
||||
}
|
||||
|
||||
public TCPSocket(string hostname, ushort port)
|
||||
{
|
||||
// create the socket
|
||||
sock = new Socket(AddressFamily.InterNetwork,
|
||||
SocketType.Stream,
|
||||
ProtocolType.Tcp);
|
||||
|
||||
receiveBuffer = new byte[sock.ReceiveBufferSize];
|
||||
//receiveBufferSegment = new ArraySegment<byte>(receiveBuffer);
|
||||
|
||||
Connect(hostname, port);
|
||||
|
||||
}
|
||||
|
||||
//private void DataSent(Task<int> task)
|
||||
//{
|
||||
// try
|
||||
// {
|
||||
// lock (sendLock)
|
||||
// {
|
||||
|
||||
// if (sendBufferQueue.Count > 0)
|
||||
// {
|
||||
// byte[] data = sendBufferQueue.Dequeue();
|
||||
// //Console.WriteLine(Encoding.UTF8.GetString(data));
|
||||
// sock.SendAsync(new ArraySegment<byte>(data), SocketFlags.None).ContinueWith(DataSent);
|
||||
// }
|
||||
|
||||
// else
|
||||
// {
|
||||
// asyncSending = false;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// if (state != SocketState.Closed && !sock.Connected)
|
||||
// {
|
||||
// state = SocketState.Terminated;
|
||||
// Close();
|
||||
// }
|
||||
|
||||
// asyncSending = false;
|
||||
|
||||
// Global.Log("TCPSocket", LogType.Error, ex.ToString());
|
||||
// }
|
||||
//}
|
||||
|
||||
public TCPSocket(IPEndPoint localEndPoint)
|
||||
{
|
||||
// create the socket
|
||||
sock = new Socket(AddressFamily.InterNetwork,
|
||||
SocketType.Stream,
|
||||
ProtocolType.Tcp);
|
||||
|
||||
receiveBuffer = new byte[sock.ReceiveBufferSize];
|
||||
|
||||
state = SocketState.Listening;
|
||||
|
||||
|
||||
// bind
|
||||
sock.Bind(localEndPoint);
|
||||
|
||||
// start listening
|
||||
sock.Listen(UInt16.MaxValue);
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public IPEndPoint RemoteEndPoint
|
||||
{
|
||||
get { return (IPEndPoint)sock.RemoteEndPoint; }
|
||||
}
|
||||
|
||||
public SocketState State
|
||||
{
|
||||
get
|
||||
{
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public TCPSocket(Socket socket)
|
||||
{
|
||||
sock = socket;
|
||||
receiveBuffer = new byte[sock.ReceiveBufferSize];
|
||||
// receiveBufferSegment = new ArraySegment<byte>(receiveBuffer);
|
||||
if (socket.Connected)
|
||||
state = SocketState.Established;
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
if (state != SocketState.Closed)// && state != SocketState.Terminated)
|
||||
{
|
||||
state = SocketState.Closed;
|
||||
|
||||
if (sock.Connected)
|
||||
{
|
||||
try
|
||||
{
|
||||
sock.Shutdown(SocketShutdown.Both);
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
sendBufferQueue?.Clear();
|
||||
Receiver?.NetworkClose(this);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Global.Log(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Send(byte[] message)
|
||||
{
|
||||
Send(message, 0, message.Length);
|
||||
}
|
||||
|
||||
public void Send(byte[] message, int offset, int size)
|
||||
{
|
||||
if (state == SocketState.Closed)// || state == SocketState.Terminated)
|
||||
return;
|
||||
|
||||
var msg = message.Clip((uint)offset, (uint)size);
|
||||
|
||||
lock (sendLock)
|
||||
{
|
||||
|
||||
if (state == SocketState.Closed)// || state == SocketState.Terminated)
|
||||
return;
|
||||
|
||||
if (!sock.Connected)
|
||||
return;
|
||||
|
||||
if (asyncSending || held)
|
||||
{
|
||||
sendBufferQueue.Enqueue(new KeyValuePair<AsyncReply<bool>, byte[]>(null, msg));// message.Clip((uint)offset, (uint)size));
|
||||
}
|
||||
else
|
||||
{
|
||||
asyncSending = true;
|
||||
try
|
||||
{
|
||||
sock.BeginSend(msg, 0, msg.Length, SocketFlags.None, sendCallback, this);
|
||||
}
|
||||
catch
|
||||
{
|
||||
asyncSending = false;
|
||||
//state = SocketState.Closed;//.Terminated;
|
||||
Close();
|
||||
}
|
||||
//sock.SendAsync(new ArraySegment<byte>(msg), SocketFlags.None).ContinueWith(DataSent);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static void Flush(TCPSocket socket)
|
||||
{
|
||||
lock (socket.sendLock)
|
||||
{
|
||||
|
||||
socket.currentReply?.Trigger(true);
|
||||
socket.currentReply = null;
|
||||
|
||||
if (socket.state == SocketState.Closed) //|| socket.state == SocketState.Terminated)
|
||||
return;
|
||||
|
||||
if (socket.sendBufferQueue.Count > 0)
|
||||
{
|
||||
var kv = socket.sendBufferQueue.Dequeue();
|
||||
|
||||
try
|
||||
{
|
||||
socket.currentReply = kv.Key;
|
||||
socket.sock.BeginSend(kv.Value, 0, kv.Value.Length, SocketFlags.None,
|
||||
socket.sendCallback, socket);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
socket.asyncSending = false;
|
||||
|
||||
try
|
||||
{
|
||||
kv.Key?.Trigger(false);
|
||||
|
||||
if (socket.state != SocketState.Closed && !socket.sock.Connected)
|
||||
{
|
||||
// socket.state = SocketState.Closed;// Terminated;
|
||||
socket.Close();
|
||||
}
|
||||
}
|
||||
catch (Exception ex2)
|
||||
{
|
||||
socket.Close();
|
||||
//socket.state = SocketState.Closed;// .Terminated;
|
||||
}
|
||||
|
||||
Global.Log("TCPSocket", LogType.Error, ex.ToString());
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
socket.asyncSending = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void SendCallback(IAsyncResult ar)
|
||||
{
|
||||
|
||||
try
|
||||
{
|
||||
var socket = (TCPSocket)ar.AsyncState;
|
||||
|
||||
socket.sock?.EndSend(ar);
|
||||
Flush(socket);
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Global.Log(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public bool Trigger(ResourceTrigger trigger)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Destroy()
|
||||
{
|
||||
Global.Counters["Sck_D_1"]++;
|
||||
|
||||
Close();
|
||||
|
||||
receiveNetworkBuffer = null;
|
||||
receiveCallback = null;
|
||||
sendCallback = null;
|
||||
sock = null;
|
||||
receiveBuffer = null;
|
||||
receiveNetworkBuffer = null;
|
||||
sendBufferQueue = null;
|
||||
|
||||
//socketArgs.Completed -= SocketArgs_Completed;
|
||||
//socketArgs.Dispose();
|
||||
//socketArgs = null;
|
||||
OnDestroy?.Invoke(this);
|
||||
OnDestroy = null;
|
||||
|
||||
Global.Counters["Sck_D_2"]++;
|
||||
}
|
||||
|
||||
public ISocket Accept()
|
||||
{
|
||||
try
|
||||
{
|
||||
var s = sock.Accept();
|
||||
return new TCPSocket(s);
|
||||
}
|
||||
catch
|
||||
{
|
||||
state = SocketState.Closed;// Terminated;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async AsyncReply<ISocket> AcceptAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var s = await sock.AcceptAsync();
|
||||
return new TCPSocket(s);
|
||||
}
|
||||
catch
|
||||
{
|
||||
state = SocketState.Closed;// Terminated;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void Hold()
|
||||
{
|
||||
held = true;
|
||||
}
|
||||
|
||||
public void Unhold()
|
||||
{
|
||||
try
|
||||
{
|
||||
Flush(this);
|
||||
//SendCallback(null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
held = false;
|
||||
}
|
||||
}
|
||||
|
||||
public AsyncReply<bool> SendAsync(byte[] message, int offset, int length)
|
||||
{
|
||||
|
||||
if (state == SocketState.Closed)// || state == SocketState.Terminated)
|
||||
return new AsyncReply<bool>(false);
|
||||
|
||||
var msg = message.Clip((uint)offset, (uint)length);
|
||||
|
||||
lock (sendLock)
|
||||
{
|
||||
if (state == SocketState.Closed)// || state == SocketState.Terminated)
|
||||
return new AsyncReply<bool>(false);
|
||||
|
||||
if (!sock.Connected)
|
||||
return new AsyncReply<bool>(false);
|
||||
|
||||
var rt = new AsyncReply<bool>();
|
||||
|
||||
if (asyncSending || held)
|
||||
{
|
||||
sendBufferQueue.Enqueue(new KeyValuePair<AsyncReply<bool>, byte[]>(rt, msg));
|
||||
}
|
||||
else
|
||||
{
|
||||
asyncSending = true;
|
||||
try
|
||||
{
|
||||
currentReply = rt;
|
||||
sock.BeginSend(msg, 0, msg.Length, SocketFlags.None, sendCallback, this);// null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
rt.TriggerError(ex);
|
||||
asyncSending = false;
|
||||
//state = SocketState.Terminated;
|
||||
Close();
|
||||
}
|
||||
//sock.SendAsync(new ArraySegment<byte>(msg), SocketFlags.None).ContinueWith(DataSent);
|
||||
}
|
||||
|
||||
return rt;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
363
Esiur/Net/Sockets/WSSocket.cs
Normal file
363
Esiur/Net/Sockets/WSSocket.cs
Normal file
@ -0,0 +1,363 @@
|
||||
/*
|
||||
|
||||
Copyright (c) 2017 Ahmed Kh. Zamil
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Net.Sockets;
|
||||
using System.Net;
|
||||
using Esiur.Net.Packets;
|
||||
using Esiur.Misc;
|
||||
using System.IO;
|
||||
using Esiur.Core;
|
||||
using Esiur.Resource;
|
||||
using Esiur.Data;
|
||||
using System.Globalization;
|
||||
|
||||
namespace Esiur.Net.Sockets
|
||||
{
|
||||
public class WSSocket : ISocket, INetworkReceiver<ISocket>
|
||||
{
|
||||
WebsocketPacket pkt_receive = new WebsocketPacket();
|
||||
WebsocketPacket pkt_send = new WebsocketPacket();
|
||||
|
||||
ISocket sock;
|
||||
NetworkBuffer receiveNetworkBuffer = new NetworkBuffer();
|
||||
NetworkBuffer sendNetworkBuffer = new NetworkBuffer();
|
||||
|
||||
object sendLock = new object();
|
||||
bool held;
|
||||
|
||||
//public event ISocketReceiveEvent OnReceive;
|
||||
//public event ISocketConnectEvent OnConnect;
|
||||
//public event ISocketCloseEvent OnClose;
|
||||
public event DestroyedEvent OnDestroy;
|
||||
|
||||
long totalSent, totalReceived;
|
||||
|
||||
bool processing = false;
|
||||
|
||||
public IPEndPoint LocalEndPoint
|
||||
{
|
||||
get { return (IPEndPoint)sock.LocalEndPoint; }
|
||||
}
|
||||
|
||||
public IPEndPoint RemoteEndPoint
|
||||
{
|
||||
get { return sock.RemoteEndPoint; }
|
||||
}
|
||||
|
||||
|
||||
public SocketState State
|
||||
{
|
||||
get
|
||||
{
|
||||
return sock.State;
|
||||
}
|
||||
}
|
||||
|
||||
public INetworkReceiver<ISocket> Receiver { get; set; }
|
||||
|
||||
public WSSocket(ISocket socket)
|
||||
{
|
||||
pkt_send.FIN = true;
|
||||
pkt_send.Mask = false;
|
||||
pkt_send.Opcode = WebsocketPacket.WSOpcode.BinaryFrame;
|
||||
sock = socket;
|
||||
|
||||
sock.Receiver = this;
|
||||
|
||||
//sock.OnClose += Sock_OnClose;
|
||||
//sock.OnConnect += Sock_OnConnect;
|
||||
//sock.OnReceive += Sock_OnReceive;
|
||||
}
|
||||
|
||||
//private void Sock_OnReceive(NetworkBuffer buffer)
|
||||
//{
|
||||
|
||||
//}
|
||||
|
||||
//private void Sock_OnConnect()
|
||||
//{
|
||||
// OnConnect?.Invoke();
|
||||
//}
|
||||
|
||||
//private void Sock_OnClose()
|
||||
//{
|
||||
// OnClose?.Invoke();
|
||||
//}
|
||||
|
||||
public void Send(WebsocketPacket packet)
|
||||
{
|
||||
lock (sendLock)
|
||||
if (packet.Compose())
|
||||
sock.Send(packet.Data);
|
||||
}
|
||||
|
||||
public void Send(byte[] message)
|
||||
{
|
||||
lock (sendLock)
|
||||
{
|
||||
if (held)
|
||||
{
|
||||
sendNetworkBuffer.Write(message);
|
||||
}
|
||||
else
|
||||
{
|
||||
totalSent += message.Length;
|
||||
//Console.WriteLine("TX " + message.Length +"/"+totalSent);// + " " + DC.ToHex(message, 0, (uint)size));
|
||||
|
||||
pkt_send.Message = message;
|
||||
|
||||
|
||||
if (pkt_send.Compose())
|
||||
sock.Send(pkt_send.Data);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void Send(byte[] message, int offset, int size)
|
||||
{
|
||||
lock (sendLock)
|
||||
{
|
||||
if (held)
|
||||
{
|
||||
sendNetworkBuffer.Write(message, (uint)offset, (uint)size);
|
||||
}
|
||||
else
|
||||
{
|
||||
totalSent += size;
|
||||
//Console.WriteLine("TX " + size + "/"+totalSent);// + " " + DC.ToHex(message, 0, (uint)size));
|
||||
|
||||
pkt_send.Message = new byte[size];
|
||||
Buffer.BlockCopy(message, offset, pkt_send.Message, 0, size);
|
||||
if (pkt_send.Compose())
|
||||
sock.Send(pkt_send.Data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void Close()
|
||||
{
|
||||
sock?.Close();
|
||||
}
|
||||
|
||||
public AsyncReply<bool> Connect(string hostname, ushort port)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
|
||||
public bool Begin()
|
||||
{
|
||||
return sock.Begin();
|
||||
}
|
||||
|
||||
public bool Trigger(ResourceTrigger trigger)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Destroy()
|
||||
{
|
||||
Close();
|
||||
//OnClose = null;
|
||||
//OnConnect = null;
|
||||
//OnReceive = null;
|
||||
receiveNetworkBuffer = null;
|
||||
//sock.OnReceive -= Sock_OnReceive;
|
||||
//sock.OnClose -= Sock_OnClose;
|
||||
//sock.OnConnect -= Sock_OnConnect;
|
||||
sock.Receiver = null;
|
||||
sock = null;
|
||||
OnDestroy?.Invoke(this);
|
||||
OnDestroy = null;
|
||||
}
|
||||
|
||||
public AsyncReply<ISocket> AcceptAsync()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void Hold()
|
||||
{
|
||||
//Console.WriteLine("WS Hold ");
|
||||
held = true;
|
||||
}
|
||||
|
||||
public void Unhold()
|
||||
{
|
||||
lock (sendLock)
|
||||
{
|
||||
held = false;
|
||||
|
||||
var message = sendNetworkBuffer.Read();
|
||||
|
||||
//Console.WriteLine("WS Unhold {0}", message == null ? 0 : message.Length);
|
||||
|
||||
if (message == null)
|
||||
return;
|
||||
|
||||
totalSent += message.Length;
|
||||
|
||||
pkt_send.Message = message;
|
||||
if (pkt_send.Compose())
|
||||
sock.Send(pkt_send.Data);
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public AsyncReply<bool> SendAsync(byte[] message, int offset, int length)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public ISocket Accept()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public AsyncReply<bool> BeginAsync()
|
||||
{
|
||||
return sock.BeginAsync();
|
||||
}
|
||||
|
||||
public void NetworkClose(ISocket sender)
|
||||
{
|
||||
Receiver?.NetworkClose(sender);
|
||||
}
|
||||
|
||||
public void NetworkReceive(ISocket sender, NetworkBuffer buffer)
|
||||
{
|
||||
|
||||
if (sock.State == SocketState.Closed)// || sock.State == SocketState.Terminated)
|
||||
return;
|
||||
|
||||
if (buffer.Protected)
|
||||
return;
|
||||
|
||||
if (processing)
|
||||
return;
|
||||
|
||||
|
||||
var msg = buffer.Read();
|
||||
|
||||
if (msg == null)
|
||||
return;
|
||||
|
||||
var wsPacketLength = pkt_receive.Parse(msg, 0, (uint)msg.Length);
|
||||
//Console.WriteLine("WSP: " + wsPacketLength);
|
||||
|
||||
if (wsPacketLength < 0)
|
||||
{
|
||||
buffer.Protect(msg, 0, (uint)msg.Length + (uint)-wsPacketLength);
|
||||
return;
|
||||
}
|
||||
|
||||
uint offset = 0;
|
||||
|
||||
while (wsPacketLength > 0)
|
||||
{
|
||||
if (pkt_receive.Opcode == WebsocketPacket.WSOpcode.ConnectionClose)
|
||||
{
|
||||
Close();
|
||||
return;
|
||||
}
|
||||
else if (pkt_receive.Opcode == WebsocketPacket.WSOpcode.Ping)
|
||||
{
|
||||
var pkt_pong = new WebsocketPacket();
|
||||
|
||||
pkt_pong.FIN = true;
|
||||
pkt_pong.Mask = false;
|
||||
pkt_pong.Opcode = WebsocketPacket.WSOpcode.Pong;
|
||||
pkt_pong.Message = pkt_receive.Message;
|
||||
offset += (uint)wsPacketLength;
|
||||
|
||||
Send(pkt_pong);
|
||||
}
|
||||
else if (pkt_receive.Opcode == WebsocketPacket.WSOpcode.Pong)
|
||||
{
|
||||
offset += (uint)wsPacketLength;
|
||||
}
|
||||
else if (pkt_receive.Opcode == WebsocketPacket.WSOpcode.BinaryFrame
|
||||
|| pkt_receive.Opcode == WebsocketPacket.WSOpcode.TextFrame
|
||||
|| pkt_receive.Opcode == WebsocketPacket.WSOpcode.ContinuationFrame)
|
||||
{
|
||||
totalReceived += pkt_receive.Message.Length;
|
||||
//Console.WriteLine("RX " + pkt_receive.Message.Length + "/" + totalReceived);// + " " + DC.ToHex(message, 0, (uint)size));
|
||||
|
||||
receiveNetworkBuffer.Write(pkt_receive.Message);
|
||||
offset += (uint)wsPacketLength;
|
||||
|
||||
//Console.WriteLine("WS IN: " + pkt_receive.Opcode.ToString() + " " + pkt_receive.Message.Length + " | " + offset + " " + string.Join(" ", pkt_receive.Message));// DC.ToHex(pkt_receive.Message));
|
||||
|
||||
}
|
||||
else
|
||||
Console.WriteLine("Unknown WS opcode:" + pkt_receive.Opcode);
|
||||
|
||||
if (offset == msg.Length)
|
||||
{
|
||||
|
||||
//OnReceive?.Invoke(receiveNetworkBuffer);
|
||||
Receiver?.NetworkReceive(this, receiveNetworkBuffer);
|
||||
return;
|
||||
}
|
||||
|
||||
wsPacketLength = pkt_receive.Parse(msg, offset, (uint)msg.Length);
|
||||
}
|
||||
|
||||
if (wsPacketLength < 0)//(offset < msg.Length) && (offset > 0))
|
||||
{
|
||||
//receiveNetworkBuffer.HoldFor(msg, offset, (uint)(msg.Length - offset), (uint)msg.Length + (uint)-wsPacketLength);
|
||||
// save the incomplete packet to the heldBuffer queue
|
||||
|
||||
buffer.HoldFor(msg, offset, (uint)(msg.Length - offset), (uint)(msg.Length - offset) + (uint)-wsPacketLength);
|
||||
|
||||
}
|
||||
|
||||
//Console.WriteLine("WS IN: " + receiveNetworkBuffer.Available);
|
||||
|
||||
//OnReceive?.Invoke(receiveNetworkBuffer);
|
||||
Receiver?.NetworkReceive(this, receiveNetworkBuffer);
|
||||
|
||||
processing = false;
|
||||
|
||||
if (buffer.Available > 0 && !buffer.Protected)
|
||||
Receiver?.NetworkReceive(this, buffer);
|
||||
//Sock_OnReceive(buffer);
|
||||
}
|
||||
|
||||
|
||||
public void NetworkConnect(ISocket sender)
|
||||
{
|
||||
Receiver?.NetworkConnect(this);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user