2017-04-21 21:04:03 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
2017-04-23 04:55:29 +00:00
|
|
|
|
using System.Net.Sockets;
|
2017-04-21 21:04:03 +00:00
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
2017-04-27 20:44:30 +00:00
|
|
|
|
namespace Kneesocks {
|
|
|
|
|
public abstract class Connection {
|
2017-04-23 04:55:29 +00:00
|
|
|
|
private TcpClient Socket;
|
2017-04-24 21:04:52 +00:00
|
|
|
|
private NetworkStream Stream;
|
|
|
|
|
|
|
|
|
|
public bool Disconnected { get; private set; } = false;
|
|
|
|
|
public string DisconnectReason { get; private set; } = null;
|
|
|
|
|
|
|
|
|
|
public bool Handshaked { get; private set; } = false;
|
|
|
|
|
private string RawClientHandshake = "";
|
|
|
|
|
private Dictionary<string, string> Headers =
|
|
|
|
|
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
2017-04-23 04:55:29 +00:00
|
|
|
|
|
|
|
|
|
public Connection(TcpClient sock) {
|
|
|
|
|
Socket = sock;
|
2017-04-24 21:04:52 +00:00
|
|
|
|
Socket.ReceiveTimeout = 1;
|
|
|
|
|
Stream = sock.GetStream();
|
2017-04-23 04:55:29 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-04-25 18:25:48 +00:00
|
|
|
|
public Connection(Connection conn) {
|
|
|
|
|
Socket = conn.Socket;
|
|
|
|
|
Stream = Socket.GetStream();
|
|
|
|
|
|
|
|
|
|
Disconnected = conn.Disconnected;
|
|
|
|
|
DisconnectReason = conn.DisconnectReason;
|
|
|
|
|
|
|
|
|
|
Handshaked = conn.Handshaked;
|
|
|
|
|
RawClientHandshake = conn.RawClientHandshake;
|
|
|
|
|
Headers = conn.Headers;
|
|
|
|
|
}
|
|
|
|
|
|
2017-04-24 21:04:52 +00:00
|
|
|
|
public void Disconnect(string reason = null) {
|
|
|
|
|
Disconnected = true;
|
|
|
|
|
DisconnectReason = reason;
|
2017-04-25 18:25:48 +00:00
|
|
|
|
|
|
|
|
|
if(Socket.Connected) {
|
|
|
|
|
Socket.SendTimeout = 1000;
|
|
|
|
|
if(!Handshaked) {
|
|
|
|
|
var raw = Encoding.ASCII.GetBytes(Handshake.DenyRequest().GetRaw());
|
|
|
|
|
Stream.Write(raw, 0, raw.Length);
|
|
|
|
|
Socket.Close();
|
|
|
|
|
} else {
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
OnClose();
|
2017-04-24 21:04:52 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// called after the client successfully handshakes
|
|
|
|
|
public virtual void OnOpen() { }
|
|
|
|
|
|
|
|
|
|
// called when the thread manager iterates through
|
|
|
|
|
// the thread list and stops on this thread
|
|
|
|
|
public virtual void OnParse() { }
|
|
|
|
|
|
|
|
|
|
// called when data has been received
|
|
|
|
|
public virtual void OnReceive(byte[] data) { }
|
2017-04-23 04:55:29 +00:00
|
|
|
|
|
2017-04-24 21:04:52 +00:00
|
|
|
|
// called when the connection is disconnected
|
|
|
|
|
public virtual void OnClose() { }
|
2017-04-21 21:04:03 +00:00
|
|
|
|
}
|
|
|
|
|
}
|