ServerLib Cleanup: removed unused classes + rename
This commit is contained in:
1 parent
e0950d9865
commit
c41af99536
14 files changed
+537
-4463
No files matched your search
@@ -1,405 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
|
||||
namespace ClientServerLib
|
||||
{
|
||||
public class CClient
|
||||
{
|
||||
private bool doConnect;
|
||||
private bool connected;
|
||||
private bool running;
|
||||
private int bufferLength = 8192;
|
||||
|
||||
private Thread clientThread;
|
||||
private IPEndPoint serverEndPoint;
|
||||
private string ip;
|
||||
private int port;
|
||||
|
||||
private CConnection connection;
|
||||
private List<SRequest> requests;
|
||||
private List<SRequest> responses;
|
||||
private Object mutexRequests = new Object();
|
||||
private OnConnectionChanged onConnectionChanged;
|
||||
private OnSend onSend;
|
||||
private OnReceived onReceived;
|
||||
|
||||
private byte[] data;
|
||||
|
||||
public bool Connected
|
||||
{
|
||||
get { return connected; }
|
||||
}
|
||||
|
||||
public CClient()
|
||||
{
|
||||
doConnect = false;
|
||||
connected = false;
|
||||
running = true;
|
||||
requests = new List<SRequest>();
|
||||
responses = new List<SRequest>();
|
||||
data = new byte[bufferLength];
|
||||
|
||||
connection = new CConnection(new TcpClient(), -1);
|
||||
}
|
||||
|
||||
public void Connect(string IP = "127.0.0.1", int Port = 3000, string Password = null,
|
||||
OnConnectionChanged OnConnectionChanged = null,
|
||||
OnSend OnSend = null,
|
||||
OnReceived OnReceived = null)
|
||||
{
|
||||
if (!doConnect)
|
||||
{
|
||||
onConnectionChanged = OnConnectionChanged;
|
||||
onSend = OnSend;
|
||||
onReceived = OnReceived;
|
||||
|
||||
ip = IP;
|
||||
port = Port;
|
||||
connection.Password = Password;
|
||||
doConnect = true;
|
||||
|
||||
if (clientThread == null)
|
||||
{
|
||||
running = true;
|
||||
clientThread = new Thread(new ThreadStart(Runner));
|
||||
clientThread.Start();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Disconnect()
|
||||
{
|
||||
if (doConnect)
|
||||
{
|
||||
doConnect = false;
|
||||
|
||||
lock (mutexRequests)
|
||||
{
|
||||
requests.Clear();
|
||||
}
|
||||
|
||||
lock (responses)
|
||||
{
|
||||
responses.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
running = false;
|
||||
|
||||
if (clientThread != null)
|
||||
clientThread.Join(100);
|
||||
|
||||
clientThread = null;
|
||||
DoDisconnect();
|
||||
}
|
||||
|
||||
public void SendMessage(byte[] Message, ResponseCallback Callback)
|
||||
{
|
||||
SRequest req = new SRequest();
|
||||
req.Command = Message;
|
||||
req.Callback = Callback;
|
||||
req.Response = null;
|
||||
|
||||
lock (mutexRequests)
|
||||
{
|
||||
requests.Add(req);
|
||||
}
|
||||
}
|
||||
|
||||
private void Runner()
|
||||
{
|
||||
while (running)
|
||||
{
|
||||
if (!connected && doConnect)
|
||||
{
|
||||
try
|
||||
{
|
||||
IPAddress resolvedIP;
|
||||
if (TryResolveIPAddress(ip, out resolvedIP))
|
||||
{
|
||||
serverEndPoint = new IPEndPoint(resolvedIP, port);
|
||||
connection.TcpClient.Connect(serverEndPoint);
|
||||
connected = true;
|
||||
RaiseOnConnectionChanged();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
DoDisconnect();
|
||||
|
||||
for (int i = 0; i < 500; i++)
|
||||
{
|
||||
if (running && doConnect)
|
||||
Thread.Sleep(10);
|
||||
else
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if (connected && !doConnect)
|
||||
{
|
||||
DoDisconnect();
|
||||
}
|
||||
|
||||
if (doConnect && connected)
|
||||
{
|
||||
try
|
||||
{
|
||||
Communicate();
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
catch
|
||||
{
|
||||
DoDisconnect();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (!doConnect && !connected)
|
||||
{
|
||||
for (int i = 0; i < 500; i++)
|
||||
{
|
||||
if (running && !doConnect)
|
||||
Thread.Sleep(10);
|
||||
else
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryResolveIPAddress(string serverNameOrURL, out IPAddress resolvedIPAddress)
|
||||
{
|
||||
bool isResolved = false;
|
||||
IPHostEntry hostEntry = null;
|
||||
IPAddress resolvIP = null;
|
||||
try
|
||||
{
|
||||
if (!IPAddress.TryParse(serverNameOrURL, out resolvIP))
|
||||
{
|
||||
hostEntry = Dns.GetHostEntry(serverNameOrURL);
|
||||
if (hostEntry != null && hostEntry.AddressList != null && hostEntry.AddressList.Length > 0)
|
||||
{
|
||||
if (hostEntry.AddressList.Length == 1)
|
||||
{
|
||||
resolvIP = hostEntry.AddressList[0];
|
||||
isResolved = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (IPAddress var in hostEntry.AddressList)
|
||||
{
|
||||
if (var.AddressFamily == AddressFamily.InterNetwork)
|
||||
{
|
||||
resolvIP = var;
|
||||
isResolved = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
isResolved = true;
|
||||
}
|
||||
catch (Exception) {}
|
||||
finally
|
||||
{
|
||||
resolvedIPAddress = resolvIP;
|
||||
}
|
||||
return isResolved;
|
||||
}
|
||||
|
||||
private void DoDisconnect()
|
||||
{
|
||||
try
|
||||
{
|
||||
connection.TcpClient.Close();
|
||||
}
|
||||
catch { }
|
||||
|
||||
connection = new CConnection(new TcpClient(), -1);
|
||||
connected = false;
|
||||
doConnect = false;
|
||||
RaiseOnConnectionChanged();
|
||||
}
|
||||
|
||||
private void Communicate()
|
||||
{
|
||||
if (connection.TcpClient == null || !connection.TcpClient.Connected)
|
||||
DoDisconnect();
|
||||
|
||||
NetworkStream clientStream = connection.TcpClient.GetStream();
|
||||
|
||||
int bytesRead;
|
||||
|
||||
if (!connection.KeySet)
|
||||
{
|
||||
bytesRead = 0;
|
||||
|
||||
try
|
||||
{
|
||||
bytesRead = clientStream.Read(data, 0, bufferLength);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (bytesRead == 0)
|
||||
return;
|
||||
|
||||
byte[] serverParam = new byte[bytesRead];
|
||||
Array.Copy(data, serverParam, bytesRead);
|
||||
RaiseOnReceived(serverParam);
|
||||
|
||||
byte[] clientResponse = connection.CreateClientKey(serverParam);
|
||||
RaiseOnSend(clientResponse);
|
||||
clientStream.Write(clientResponse, 0, clientResponse.Length);
|
||||
clientStream.Flush();
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
while (requests.Count > 0)
|
||||
{
|
||||
SRequest res = HandleRequest(requests[0]);
|
||||
lock (responses)
|
||||
{
|
||||
responses.Add(res);
|
||||
}
|
||||
|
||||
lock (mutexRequests)
|
||||
{
|
||||
requests.RemoveAt(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { };
|
||||
|
||||
lock (responses)
|
||||
{
|
||||
while (responses.Count > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (responses[0].Callback != null)
|
||||
responses[0].Callback(responses[0].Response);
|
||||
}
|
||||
finally
|
||||
{
|
||||
responses.RemoveAt(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private SRequest HandleRequest(SRequest request)
|
||||
{
|
||||
SRequest response = new SRequest();
|
||||
response.Command = request.Command;
|
||||
response.Callback = request.Callback;
|
||||
response.Response = null;
|
||||
|
||||
NetworkStream clientStream = connection.TcpClient.GetStream();
|
||||
|
||||
RaiseOnSend(request.Command);
|
||||
byte[] encrypted = connection.Encrypt(request.Command);
|
||||
|
||||
int sendBytes = 0;
|
||||
while(sendBytes < encrypted.Length)
|
||||
{
|
||||
int bytesToSend = encrypted.Length - sendBytes;
|
||||
if (bytesToSend > bufferLength)
|
||||
bytesToSend = bufferLength;
|
||||
|
||||
clientStream.Write(encrypted, sendBytes, bytesToSend);
|
||||
sendBytes += bytesToSend;
|
||||
}
|
||||
clientStream.Flush();
|
||||
|
||||
byte[] data = new byte[bufferLength];
|
||||
int bytesRead = 0;
|
||||
|
||||
try
|
||||
{
|
||||
bytesRead = clientStream.Read(data, 0, bufferLength);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return response;
|
||||
}
|
||||
|
||||
if (bytesRead == 0)
|
||||
return response;
|
||||
|
||||
int messageLength = BitConverter.ToInt32(data, 0);
|
||||
while (messageLength > bytesRead)
|
||||
{
|
||||
if (data.Length < messageLength + bufferLength)
|
||||
Array.Resize<byte>(ref data, messageLength + bufferLength);
|
||||
bytesRead += clientStream.Read(data, bytesRead, bufferLength);
|
||||
}
|
||||
|
||||
encrypted = new byte[bytesRead];
|
||||
Array.Copy(data, encrypted, bytesRead);
|
||||
response.Response = connection.Decrypt(encrypted);
|
||||
RaiseOnReceived(response.Response);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
private void RaiseOnConnectionChanged()
|
||||
{
|
||||
if (onConnectionChanged == null)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
onConnectionChanged(connected);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine (e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void RaiseOnSend(byte[] Message)
|
||||
{
|
||||
if (onSend == null)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
onSend(Message);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private void RaiseOnReceived(byte[] Message)
|
||||
{
|
||||
if (onReceived == null)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
onReceived(Message);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,307 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
using DiffieHellman;
|
||||
|
||||
namespace ClientServerLib
|
||||
{
|
||||
internal class CConnection
|
||||
{
|
||||
private bool keySet;
|
||||
private byte[] key;
|
||||
private bool encryption;
|
||||
private string password;
|
||||
private CDiffieHellman dh;
|
||||
private UTF8Encoding encoder;
|
||||
private int connectionID;
|
||||
private static SHA256Managed SHA256 = new SHA256Managed();
|
||||
|
||||
public TcpClient TcpClient;
|
||||
|
||||
public bool KeySet
|
||||
{
|
||||
get { return keySet; }
|
||||
}
|
||||
|
||||
public int ConnectionID
|
||||
{
|
||||
get { return connectionID; }
|
||||
}
|
||||
|
||||
public string Password
|
||||
{
|
||||
set
|
||||
{
|
||||
password = value;
|
||||
encryption = value != null;
|
||||
keySet = false;
|
||||
}
|
||||
}
|
||||
|
||||
public CConnection(TcpClient client, int ConnectionID, string Password = null)
|
||||
{
|
||||
TcpClient = client;
|
||||
client.NoDelay = true;
|
||||
keySet = false;
|
||||
encryption = Password != null;
|
||||
password = Password;
|
||||
connectionID = ConnectionID;
|
||||
encoder = new UTF8Encoding();
|
||||
key = null;
|
||||
}
|
||||
|
||||
public byte[] GetKeyParams()
|
||||
{
|
||||
if (!encryption)
|
||||
{
|
||||
return encoder.GetBytes("NO ENCRYPTION");
|
||||
}
|
||||
|
||||
if (dh == null)
|
||||
dh = new CDiffieHellman(256).GenerateRequest();
|
||||
|
||||
return encoder.GetBytes(dh.ToString());
|
||||
}
|
||||
|
||||
public byte[] CreateClientKey(byte[] serverParam)
|
||||
{
|
||||
if (serverParam == null)
|
||||
return null;
|
||||
|
||||
string response = encoder.GetString(serverParam, 0, serverParam.Length);
|
||||
if (response == "NO ENCRYPTION")
|
||||
{
|
||||
encryption = false;
|
||||
keySet = true;
|
||||
key = null;
|
||||
return encoder.GetBytes(response);
|
||||
}
|
||||
|
||||
dh = new CDiffieHellman(256).GenerateResponse(response);
|
||||
key = _BuildHash(dh.Key, password);
|
||||
keySet = true;
|
||||
encryption = true;
|
||||
return encoder.GetBytes(dh.ToString());
|
||||
}
|
||||
|
||||
public void CreateServerKey(byte[] clientResponse)
|
||||
{
|
||||
string response = encoder.GetString(clientResponse, 0, clientResponse.Length);
|
||||
|
||||
if (response == "NO ENCRYPTION")
|
||||
{
|
||||
keySet = true;
|
||||
key = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (dh == null)
|
||||
return;
|
||||
|
||||
dh.HandleResponse(response);
|
||||
key = _BuildHash(dh.Key, password);
|
||||
keySet = true;
|
||||
}
|
||||
|
||||
public byte[] Encrypt(byte[] Data)
|
||||
{
|
||||
return _Encrypt(_Compress(Data));
|
||||
}
|
||||
|
||||
public byte[] Decrypt(byte[] Data)
|
||||
{
|
||||
return _Decompress(_Decrypt(Data));
|
||||
}
|
||||
|
||||
private byte[] _BuildHash(byte[] Key, string Password)
|
||||
{
|
||||
if (Key == null || Password == null)
|
||||
return null;
|
||||
|
||||
byte[] hash = SHA256.ComputeHash(encoder.GetBytes(Password));
|
||||
byte[] serial = new byte[Key.Length + hash.Length];
|
||||
Array.Copy(Key, serial, Key.Length);
|
||||
Array.Copy(hash, 0, serial, Key.Length, hash.Length);
|
||||
|
||||
return SHA256.ComputeHash(serial);
|
||||
}
|
||||
|
||||
private byte[] _Encrypt(byte[] Data)
|
||||
{
|
||||
if (Data == null || (!keySet && encryption))
|
||||
return Data;
|
||||
|
||||
byte[] dataLength = BitConverter.GetBytes(Data.Length);
|
||||
|
||||
if (!encryption)
|
||||
{
|
||||
int len = 4 + dataLength.Length + Data.Length;
|
||||
byte[] messageLength = BitConverter.GetBytes(len);
|
||||
|
||||
using (var stream = new MemoryStream())
|
||||
{
|
||||
stream.Write(messageLength, 0, messageLength.Length);
|
||||
stream.Write(dataLength, 0, dataLength.Length);
|
||||
stream.Write(Data, 0, Data.Length);
|
||||
|
||||
return stream.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
using (Aes aes = new AesManaged())
|
||||
{
|
||||
aes.Key = key;
|
||||
aes.GenerateIV();
|
||||
|
||||
using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
|
||||
using (var memoryStream = new MemoryStream())
|
||||
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
|
||||
{
|
||||
cryptoStream.Write(Data, 0, Data.Length);
|
||||
cryptoStream.FlushFinalBlock();
|
||||
|
||||
byte[] encrypted = memoryStream.ToArray();
|
||||
|
||||
int len = 4 + aes.IV.Length + dataLength.Length + encrypted.Length;
|
||||
byte[] messageLength = BitConverter.GetBytes(len);
|
||||
|
||||
using (var stream = new MemoryStream())
|
||||
{
|
||||
stream.Write(messageLength, 0, messageLength.Length);
|
||||
stream.Write(aes.IV, 0, aes.IV.Length);
|
||||
stream.Write(dataLength, 0, dataLength.Length);
|
||||
stream.Write(encrypted, 0, encrypted.Length);
|
||||
|
||||
return stream.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] _Decrypt(byte[] Data)
|
||||
{
|
||||
if (Data == null || (!keySet && encryption))
|
||||
return Data;
|
||||
|
||||
|
||||
int messageLength = BitConverter.ToInt32(Data, 0);
|
||||
if (messageLength > Data.Length)
|
||||
return null;
|
||||
|
||||
int dataLength;
|
||||
|
||||
if (!encryption)
|
||||
{
|
||||
dataLength = BitConverter.ToInt32(Data, 4);
|
||||
|
||||
byte[] message = new byte[dataLength];
|
||||
Array.Copy(Data, 8, message, 0, dataLength);
|
||||
return message;
|
||||
}
|
||||
|
||||
if (Data.Length < 25)
|
||||
return null;
|
||||
|
||||
byte[] IV = new byte[16];
|
||||
Array.Copy(Data, 4, IV, 0, 16);
|
||||
|
||||
dataLength = BitConverter.ToInt32(Data, 20);
|
||||
|
||||
using (Aes aes = new AesManaged())
|
||||
{
|
||||
aes.Key = key;
|
||||
aes.IV = IV;
|
||||
|
||||
byte[] encrypted = new byte[messageLength - 24];
|
||||
Array.Copy(Data, 24, encrypted, 0, encrypted.Length);
|
||||
|
||||
try
|
||||
{
|
||||
using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
|
||||
using (var memoryStream = new MemoryStream())
|
||||
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Write))
|
||||
{
|
||||
cryptoStream.Write(encrypted, 0, encrypted.Length);
|
||||
cryptoStream.FlushFinalBlock();
|
||||
cryptoStream.Close();
|
||||
|
||||
byte[] decrypted = memoryStream.ToArray();
|
||||
byte[] message = new byte[dataLength];
|
||||
Array.Copy(decrypted, message, dataLength);
|
||||
|
||||
return message;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] _Compress(byte[] Data)
|
||||
{
|
||||
if (Data == null)
|
||||
return Data;
|
||||
|
||||
using (var compressed = new MemoryStream())
|
||||
{
|
||||
using (var gz = new GZipStream(compressed, CompressionMode.Compress, true))
|
||||
{
|
||||
gz.Write(Data, 0, Data.Length);
|
||||
}
|
||||
|
||||
byte[] result = null;
|
||||
|
||||
if (compressed.Length < Data.Length)
|
||||
{
|
||||
result = new byte[compressed.Length + 1];
|
||||
result[0] = 1; //data stream is compressed
|
||||
compressed.Position = 0;
|
||||
compressed.Read(result, 1, (int)compressed.Length);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = new byte[Data.Length + 1];
|
||||
result[0] = 0; //data stream is not compressed
|
||||
Array.Copy(Data, 0, result, 1, Data.Length);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] _Decompress(byte[] Data)
|
||||
{
|
||||
if (Data == null)
|
||||
return Data;
|
||||
|
||||
if (Data[0] == 0) //not compressed
|
||||
{
|
||||
byte[] result = new byte[Data.Length - 1];
|
||||
Array.Copy(Data, 1, result, 0, result.Length);
|
||||
return result;
|
||||
}
|
||||
|
||||
using (var inStream = new MemoryStream())
|
||||
{
|
||||
inStream.Write(Data, 1, Data.Length - 1);
|
||||
inStream.Position = 0;
|
||||
|
||||
using (var outStream = new MemoryStream())
|
||||
{
|
||||
using (var gz = new GZipStream(inStream, CompressionMode.Decompress, true))
|
||||
gz.CopyTo(outStream);
|
||||
|
||||
return outStream.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,125 +1,125 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Timers;
|
||||
|
||||
namespace ClientServerLib
|
||||
{
|
||||
public delegate void OnServerDiscovered(string IPAddress, string Hostname);
|
||||
|
||||
public class CDiscover
|
||||
{
|
||||
public static readonly string sTimeout = "Timeout";
|
||||
public static readonly string sFinished = "Finished";
|
||||
|
||||
private string _Keyword;
|
||||
private string _BroadcastAddress;
|
||||
private int _Port;
|
||||
|
||||
private Thread _DiscoverThread;
|
||||
private bool _DiscoverRunning;
|
||||
private OnServerDiscovered _OnDiscovered;
|
||||
|
||||
|
||||
private System.Timers.Timer _BroadcastTimer;
|
||||
|
||||
public CDiscover(int Port, string Keyword, string BroadcastAddress = "255.255.255.255")
|
||||
{
|
||||
_BroadcastAddress = BroadcastAddress;
|
||||
_Port = Port;
|
||||
_Keyword = Keyword;
|
||||
|
||||
_DiscoverRunning = false;
|
||||
_BroadcastTimer = new System.Timers.Timer();
|
||||
_BroadcastTimer.Elapsed += new ElapsedEventHandler(OnBroadcastEvent);
|
||||
_BroadcastTimer.Interval = 2500;
|
||||
}
|
||||
|
||||
public void StartBroadcasting()
|
||||
{
|
||||
_BroadcastTimer.Start();
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
_BroadcastTimer.Stop();
|
||||
_DiscoverRunning = false;
|
||||
}
|
||||
|
||||
public void Discover(OnServerDiscovered OnDiscovered, int Timeout = 5000)
|
||||
{
|
||||
if (_DiscoverRunning)
|
||||
return;
|
||||
|
||||
_DiscoverRunning = true;
|
||||
_DiscoverThread = new Thread(() => _Discover(Timeout));
|
||||
_OnDiscovered = OnDiscovered;
|
||||
_DiscoverThread.Start();
|
||||
}
|
||||
|
||||
private void OnBroadcastEvent(object source, ElapsedEventArgs e)
|
||||
{
|
||||
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
|
||||
s.EnableBroadcast = true;
|
||||
IPAddress broadcast = IPAddress.Parse(_BroadcastAddress);
|
||||
byte[] sendbuf = Encoding.UTF8.GetBytes(_Keyword);
|
||||
IPEndPoint ep = new IPEndPoint(broadcast, _Port);
|
||||
|
||||
s.SendTo(sendbuf, ep);
|
||||
s.Close();
|
||||
}
|
||||
|
||||
private void _Discover(int Timeout)
|
||||
{
|
||||
UdpClient listener = null;
|
||||
Stopwatch timer = new Stopwatch();
|
||||
|
||||
List<string> knownServer = new List<string>();
|
||||
bool foundSomething = false;
|
||||
timer.Start();
|
||||
while (_DiscoverRunning && timer.ElapsedMilliseconds < Timeout * 2)
|
||||
{
|
||||
try
|
||||
{
|
||||
listener = new UdpClient(_Port);
|
||||
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, _Port);
|
||||
listener.Client.ReceiveTimeout = Timeout;
|
||||
|
||||
byte[] bytes = listener.Receive(ref groupEP);
|
||||
string message = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
|
||||
|
||||
foundSomething = true;
|
||||
if (!knownServer.Contains(groupEP.Address.ToString()))
|
||||
{
|
||||
knownServer.Add(groupEP.Address.ToString());
|
||||
if (_OnDiscovered != null)
|
||||
{
|
||||
IPHostEntry e = Dns.GetHostEntry(groupEP.Address);
|
||||
string hostname = e.HostName;
|
||||
|
||||
_OnDiscovered(groupEP.Address.ToString(), hostname);
|
||||
}
|
||||
}
|
||||
|
||||
listener.Close();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
if (listener != null)
|
||||
listener.Close();
|
||||
}
|
||||
}
|
||||
_DiscoverRunning = false;
|
||||
|
||||
if (!foundSomething)
|
||||
_OnDiscovered(sTimeout, String.Empty);
|
||||
else
|
||||
_OnDiscovered(sFinished, String.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Timers;
|
||||
|
||||
namespace ServerLib
|
||||
{
|
||||
public delegate void OnServerDiscovered(string IPAddress, string Hostname);
|
||||
|
||||
public class CDiscover
|
||||
{
|
||||
public static readonly string sTimeout = "Timeout";
|
||||
public static readonly string sFinished = "Finished";
|
||||
|
||||
private string _Keyword;
|
||||
private string _BroadcastAddress;
|
||||
private int _Port;
|
||||
|
||||
private Thread _DiscoverThread;
|
||||
private bool _DiscoverRunning;
|
||||
private OnServerDiscovered _OnDiscovered;
|
||||
|
||||
|
||||
private System.Timers.Timer _BroadcastTimer;
|
||||
|
||||
public CDiscover(int Port, string Keyword, string BroadcastAddress = "255.255.255.255")
|
||||
{
|
||||
_BroadcastAddress = BroadcastAddress;
|
||||
_Port = Port;
|
||||
_Keyword = Keyword;
|
||||
|
||||
_DiscoverRunning = false;
|
||||
_BroadcastTimer = new System.Timers.Timer();
|
||||
_BroadcastTimer.Elapsed += new ElapsedEventHandler(OnBroadcastEvent);
|
||||
_BroadcastTimer.Interval = 2500;
|
||||
}
|
||||
|
||||
public void StartBroadcasting()
|
||||
{
|
||||
_BroadcastTimer.Start();
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
_BroadcastTimer.Stop();
|
||||
_DiscoverRunning = false;
|
||||
}
|
||||
|
||||
public void Discover(OnServerDiscovered OnDiscovered, int Timeout = 5000)
|
||||
{
|
||||
if (_DiscoverRunning)
|
||||
return;
|
||||
|
||||
_DiscoverRunning = true;
|
||||
_DiscoverThread = new Thread(() => _Discover(Timeout));
|
||||
_OnDiscovered = OnDiscovered;
|
||||
_DiscoverThread.Start();
|
||||
}
|
||||
|
||||
private void OnBroadcastEvent(object source, ElapsedEventArgs e)
|
||||
{
|
||||
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
|
||||
s.EnableBroadcast = true;
|
||||
IPAddress broadcast = IPAddress.Parse(_BroadcastAddress);
|
||||
byte[] sendbuf = Encoding.UTF8.GetBytes(_Keyword);
|
||||
IPEndPoint ep = new IPEndPoint(broadcast, _Port);
|
||||
|
||||
s.SendTo(sendbuf, ep);
|
||||
s.Close();
|
||||
}
|
||||
|
||||
private void _Discover(int Timeout)
|
||||
{
|
||||
UdpClient listener = null;
|
||||
Stopwatch timer = new Stopwatch();
|
||||
|
||||
List<string> knownServer = new List<string>();
|
||||
bool foundSomething = false;
|
||||
timer.Start();
|
||||
while (_DiscoverRunning && timer.ElapsedMilliseconds < Timeout * 2)
|
||||
{
|
||||
try
|
||||
{
|
||||
listener = new UdpClient(_Port);
|
||||
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, _Port);
|
||||
listener.Client.ReceiveTimeout = Timeout;
|
||||
|
||||
byte[] bytes = listener.Receive(ref groupEP);
|
||||
string message = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
|
||||
|
||||
foundSomething = true;
|
||||
if (!knownServer.Contains(groupEP.Address.ToString()))
|
||||
{
|
||||
knownServer.Add(groupEP.Address.ToString());
|
||||
if (_OnDiscovered != null)
|
||||
{
|
||||
IPHostEntry e = Dns.GetHostEntry(groupEP.Address);
|
||||
string hostname = e.HostName;
|
||||
|
||||
_OnDiscovered(groupEP.Address.ToString(), hostname);
|
||||
}
|
||||
}
|
||||
|
||||
listener.Close();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
if (listener != null)
|
||||
listener.Close();
|
||||
}
|
||||
}
|
||||
_DiscoverRunning = false;
|
||||
|
||||
if (!foundSomething)
|
||||
_OnDiscovered(sTimeout, String.Empty);
|
||||
else
|
||||
_OnDiscovered(sFinished, String.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ using System.Security.Cryptography.X509Certificates;
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
|
||||
namespace ClientServerLib
|
||||
namespace ServerLib
|
||||
{
|
||||
public class CServer
|
||||
{
|
||||
|
||||
@@ -1,282 +1,282 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.ServiceModel;
|
||||
using System.Text;
|
||||
using System.ServiceModel.Web;
|
||||
using System.Web.Services;
|
||||
using System.IO;
|
||||
|
||||
namespace ClientServerLib
|
||||
{
|
||||
[ServiceContract]
|
||||
public interface ICWebservice
|
||||
{
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/sendKeyEvent?key={key}")]
|
||||
bool sendKeyEvent(string key);
|
||||
|
||||
#region profile
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "POST",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/sendProfile")]
|
||||
bool sendProfile(ProfileData profile);
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/getProfile?profileId={profileId}")]
|
||||
ProfileData getProfile(int profileId);
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/getProfileList")]
|
||||
ProfileData[] getProfileList();
|
||||
|
||||
#endregion
|
||||
|
||||
#region photo
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "POST",
|
||||
RequestFormat = WebMessageFormat.Json,
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/sendPhoto")]
|
||||
bool sendPhoto(PhotoData photo);
|
||||
|
||||
#endregion
|
||||
|
||||
#region website
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "")]
|
||||
Stream Index();
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/js/{filename}")]
|
||||
Stream GetJsFile(String filename);
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/css/{filename}")]
|
||||
Stream GetCssFile(String filename);
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/css/images/{filename}")]
|
||||
Stream GetCssImageFile(String filename);
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/img/{filename}")]
|
||||
Stream GetImgFile(String filename);
|
||||
|
||||
#endregion
|
||||
|
||||
#region songs
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/getSong?songId={songId}")]
|
||||
SongInfo getSong(int songId);
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/getCurrentSongId")]
|
||||
int getCurrentSongId();
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/getAllSongs")]
|
||||
SongInfo[] getAllSongs();
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
class CWebservice : ICWebservice
|
||||
{
|
||||
public CWebservice()
|
||||
{
|
||||
}
|
||||
|
||||
public bool sendKeyEvent(string key)
|
||||
{
|
||||
if (CServer.SendKeyEvent == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return CServer.SendKeyEvent(key);
|
||||
}
|
||||
|
||||
#region profile
|
||||
|
||||
public bool sendProfile(ProfileData profile)
|
||||
{
|
||||
if (CServer.SendProfileData == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return CServer.SendProfileData(profile);
|
||||
}
|
||||
|
||||
public ProfileData getProfile(int profileId)
|
||||
{
|
||||
if (CServer.GetProfileData == null)
|
||||
{
|
||||
return new ProfileData();
|
||||
}
|
||||
return CServer.GetProfileData(profileId);
|
||||
}
|
||||
|
||||
public ProfileData[] getProfileList()
|
||||
{
|
||||
if (CServer.GetProfileList == null)
|
||||
{
|
||||
return new ProfileData[] { };
|
||||
}
|
||||
return CServer.GetProfileList();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region photo
|
||||
|
||||
public bool sendPhoto(PhotoData photo)
|
||||
{
|
||||
return CServer.SendPhoto(photo);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region website
|
||||
|
||||
public Stream Index()
|
||||
{
|
||||
if (WebOperationContext.Current != null)
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
|
||||
}
|
||||
|
||||
return new MemoryStream(CServer.GetSiteFile("index.html"));
|
||||
}
|
||||
|
||||
public Stream GetJsFile(string filename)
|
||||
{
|
||||
if (WebOperationContext.Current != null)
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.ContentType = "text/javascript";
|
||||
}
|
||||
|
||||
byte[] data = CServer.GetSiteFile("js/" + filename);
|
||||
|
||||
if (data != null)
|
||||
{
|
||||
return new MemoryStream(data);
|
||||
}
|
||||
else
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Stream GetCssFile(string filename)
|
||||
{
|
||||
if (WebOperationContext.Current != null)
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.ContentType = "text/css";
|
||||
}
|
||||
|
||||
byte[] data = CServer.GetSiteFile("css/" + filename);
|
||||
|
||||
if (data != null)
|
||||
{
|
||||
return new MemoryStream(data);
|
||||
}
|
||||
else
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound;
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public Stream GetCssImageFile(string filename)
|
||||
{
|
||||
if (WebOperationContext.Current != null)
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.ContentType = "image/png";
|
||||
}
|
||||
|
||||
byte[] data = CServer.GetSiteFile("css\\images\\" + filename);
|
||||
|
||||
if (data != null)
|
||||
{
|
||||
return new MemoryStream(data);
|
||||
}
|
||||
else
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Stream GetImgFile(string filename)
|
||||
{
|
||||
if (WebOperationContext.Current != null)
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.ContentType = "image/png";
|
||||
}
|
||||
|
||||
byte[] data = CServer.GetSiteFile("img/" + filename);
|
||||
|
||||
if (data != null)
|
||||
{
|
||||
return new MemoryStream(data);
|
||||
}
|
||||
else
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region songs
|
||||
|
||||
public SongInfo getSong(int songId)
|
||||
{
|
||||
return CServer.GetSong(songId);
|
||||
}
|
||||
|
||||
public int getCurrentSongId()
|
||||
{
|
||||
return CServer.GetCurrentSongId();
|
||||
}
|
||||
|
||||
public SongInfo[] getAllSongs()
|
||||
{
|
||||
return CServer.GetAllSongs();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.ServiceModel;
|
||||
using System.Text;
|
||||
using System.ServiceModel.Web;
|
||||
using System.Web.Services;
|
||||
using System.IO;
|
||||
|
||||
namespace ServerLib
|
||||
{
|
||||
[ServiceContract]
|
||||
public interface ICWebservice
|
||||
{
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/sendKeyEvent?key={key}")]
|
||||
bool sendKeyEvent(string key);
|
||||
|
||||
#region profile
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "POST",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/sendProfile")]
|
||||
bool sendProfile(ProfileData profile);
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/getProfile?profileId={profileId}")]
|
||||
ProfileData getProfile(int profileId);
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/getProfileList")]
|
||||
ProfileData[] getProfileList();
|
||||
|
||||
#endregion
|
||||
|
||||
#region photo
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "POST",
|
||||
RequestFormat = WebMessageFormat.Json,
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/sendPhoto")]
|
||||
bool sendPhoto(PhotoData photo);
|
||||
|
||||
#endregion
|
||||
|
||||
#region website
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "")]
|
||||
Stream Index();
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/js/{filename}")]
|
||||
Stream GetJsFile(String filename);
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/css/{filename}")]
|
||||
Stream GetCssFile(String filename);
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/css/images/{filename}")]
|
||||
Stream GetCssImageFile(String filename);
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/img/{filename}")]
|
||||
Stream GetImgFile(String filename);
|
||||
|
||||
#endregion
|
||||
|
||||
#region songs
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/getSong?songId={songId}")]
|
||||
SongInfo getSong(int songId);
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/getCurrentSongId")]
|
||||
int getCurrentSongId();
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(Method = "GET",
|
||||
ResponseFormat = WebMessageFormat.Json,
|
||||
UriTemplate = "/getAllSongs")]
|
||||
SongInfo[] getAllSongs();
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
class CWebservice : ICWebservice
|
||||
{
|
||||
public CWebservice()
|
||||
{
|
||||
}
|
||||
|
||||
public bool sendKeyEvent(string key)
|
||||
{
|
||||
if (CServer.SendKeyEvent == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return CServer.SendKeyEvent(key);
|
||||
}
|
||||
|
||||
#region profile
|
||||
|
||||
public bool sendProfile(ProfileData profile)
|
||||
{
|
||||
if (CServer.SendProfileData == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return CServer.SendProfileData(profile);
|
||||
}
|
||||
|
||||
public ProfileData getProfile(int profileId)
|
||||
{
|
||||
if (CServer.GetProfileData == null)
|
||||
{
|
||||
return new ProfileData();
|
||||
}
|
||||
return CServer.GetProfileData(profileId);
|
||||
}
|
||||
|
||||
public ProfileData[] getProfileList()
|
||||
{
|
||||
if (CServer.GetProfileList == null)
|
||||
{
|
||||
return new ProfileData[] { };
|
||||
}
|
||||
return CServer.GetProfileList();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region photo
|
||||
|
||||
public bool sendPhoto(PhotoData photo)
|
||||
{
|
||||
return CServer.SendPhoto(photo);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region website
|
||||
|
||||
public Stream Index()
|
||||
{
|
||||
if (WebOperationContext.Current != null)
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
|
||||
}
|
||||
|
||||
return new MemoryStream(CServer.GetSiteFile("index.html"));
|
||||
}
|
||||
|
||||
public Stream GetJsFile(string filename)
|
||||
{
|
||||
if (WebOperationContext.Current != null)
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.ContentType = "text/javascript";
|
||||
}
|
||||
|
||||
byte[] data = CServer.GetSiteFile("js/" + filename);
|
||||
|
||||
if (data != null)
|
||||
{
|
||||
return new MemoryStream(data);
|
||||
}
|
||||
else
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Stream GetCssFile(string filename)
|
||||
{
|
||||
if (WebOperationContext.Current != null)
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.ContentType = "text/css";
|
||||
}
|
||||
|
||||
byte[] data = CServer.GetSiteFile("css/" + filename);
|
||||
|
||||
if (data != null)
|
||||
{
|
||||
return new MemoryStream(data);
|
||||
}
|
||||
else
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound;
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public Stream GetCssImageFile(string filename)
|
||||
{
|
||||
if (WebOperationContext.Current != null)
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.ContentType = "image/png";
|
||||
}
|
||||
|
||||
byte[] data = CServer.GetSiteFile("css\\images\\" + filename);
|
||||
|
||||
if (data != null)
|
||||
{
|
||||
return new MemoryStream(data);
|
||||
}
|
||||
else
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Stream GetImgFile(string filename)
|
||||
{
|
||||
if (WebOperationContext.Current != null)
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.ContentType = "image/png";
|
||||
}
|
||||
|
||||
byte[] data = CServer.GetSiteFile("img/" + filename);
|
||||
|
||||
if (data != null)
|
||||
{
|
||||
return new MemoryStream(data);
|
||||
}
|
||||
else
|
||||
{
|
||||
WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region songs
|
||||
|
||||
public SongInfo getSong(int songId)
|
||||
{
|
||||
return CServer.GetSong(songId);
|
||||
}
|
||||
|
||||
public int getCurrentSongId()
|
||||
{
|
||||
return CServer.GetCurrentSongId();
|
||||
}
|
||||
|
||||
public SongInfo[] getAllSongs()
|
||||
{
|
||||
return CServer.GetAllSongs();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,124 +1,124 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Drawing;
|
||||
using System.IO;
|
||||
using System.Drawing.Imaging;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace ClientServerLib
|
||||
{
|
||||
public delegate bool SendKeyEventDelegate(string key);
|
||||
|
||||
|
||||
#region profile
|
||||
|
||||
public delegate ProfileData GetProfileDataDelegate(int profileId);
|
||||
public delegate bool SendProfileDataDelegate(ProfileData profile);
|
||||
public delegate ProfileData[] GetProfileListDelegate();
|
||||
|
||||
[DataContract]
|
||||
public struct ProfileData
|
||||
{
|
||||
[DataMember]
|
||||
public Base64Image Avatar;
|
||||
[DataMember]
|
||||
public string PlayerName;
|
||||
[DataMember]
|
||||
public int Type;
|
||||
[DataMember]
|
||||
public int Difficulty;
|
||||
[DataMember]
|
||||
public int ProfileId;
|
||||
[DataMember]
|
||||
public bool IsEditable;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region photo
|
||||
|
||||
public delegate bool SendPhotoDelegate(PhotoData photo);
|
||||
|
||||
[DataContract]
|
||||
public struct PhotoData
|
||||
{
|
||||
[DataMember]
|
||||
public Base64Image Photo;
|
||||
//Add infomation about the user who took this image??
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region website
|
||||
|
||||
public delegate byte[] GetSiteFileDelegate(string filename);
|
||||
|
||||
#endregion
|
||||
|
||||
[DataContract]
|
||||
public class Base64Image
|
||||
{
|
||||
[DataMember]
|
||||
private string base64Data = "";
|
||||
|
||||
public Base64Image(Image img, ImageFormat format)
|
||||
{
|
||||
MemoryStream ms = new MemoryStream();
|
||||
img.Save(ms, format);
|
||||
string formatString = ImageCodecInfo.GetImageEncoders().FirstOrDefault(x => x.FormatID == format.Guid).FilenameExtension.Replace("*.", "").ToLower();
|
||||
base64Data = "data:image/" + formatString + ";base64," + Convert.ToBase64String(ms.ToArray());
|
||||
}
|
||||
|
||||
public Image getImage()
|
||||
{
|
||||
string onlyBase64Data = base64Data.Substring(base64Data.IndexOf(";base64,") + (";base64,").Length);
|
||||
byte[] imageData = Convert.FromBase64String(onlyBase64Data);
|
||||
MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length);
|
||||
ms.Write(imageData, 0, imageData.Length);
|
||||
Image image = Image.FromStream(ms, true);
|
||||
return image;
|
||||
}
|
||||
|
||||
public string getImageType()
|
||||
{
|
||||
Match match = Regex.Match(base64Data, "(?<=data:image/)[a-zA-Z]+(?=;base64)");
|
||||
return match.Success ? match.Groups[0].Value : "";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
#region songs
|
||||
|
||||
public delegate SongInfo GetSongDelegate(int songId);
|
||||
|
||||
public delegate SongInfo[] GetAllSongsDelegate();
|
||||
|
||||
public delegate int GetCurrentSongIdDelegate();
|
||||
|
||||
[DataContract]
|
||||
public struct SongInfo
|
||||
{
|
||||
[DataMember]
|
||||
public string Title;
|
||||
[DataMember]
|
||||
public string Artist;
|
||||
[DataMember]
|
||||
public Base64Image Cover;
|
||||
[DataMember]
|
||||
public string Genre { get; set; }
|
||||
[DataMember]
|
||||
public string Language { get; set; }
|
||||
[DataMember]
|
||||
public string Year { get; set; }
|
||||
[DataMember]
|
||||
public bool IsDuet { get; set; }
|
||||
[DataMember]
|
||||
public int SongId { get; set; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Drawing;
|
||||
using System.IO;
|
||||
using System.Drawing.Imaging;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace ServerLib
|
||||
{
|
||||
public delegate bool SendKeyEventDelegate(string key);
|
||||
|
||||
|
||||
#region profile
|
||||
|
||||
public delegate ProfileData GetProfileDataDelegate(int profileId);
|
||||
public delegate bool SendProfileDataDelegate(ProfileData profile);
|
||||
public delegate ProfileData[] GetProfileListDelegate();
|
||||
|
||||
[DataContract]
|
||||
public struct ProfileData
|
||||
{
|
||||
[DataMember]
|
||||
public Base64Image Avatar;
|
||||
[DataMember]
|
||||
public string PlayerName;
|
||||
[DataMember]
|
||||
public int Type;
|
||||
[DataMember]
|
||||
public int Difficulty;
|
||||
[DataMember]
|
||||
public int ProfileId;
|
||||
[DataMember]
|
||||
public bool IsEditable;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region photo
|
||||
|
||||
public delegate bool SendPhotoDelegate(PhotoData photo);
|
||||
|
||||
[DataContract]
|
||||
public struct PhotoData
|
||||
{
|
||||
[DataMember]
|
||||
public Base64Image Photo;
|
||||
//Add infomation about the user who took this image??
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region website
|
||||
|
||||
public delegate byte[] GetSiteFileDelegate(string filename);
|
||||
|
||||
#endregion
|
||||
|
||||
[DataContract]
|
||||
public class Base64Image
|
||||
{
|
||||
[DataMember]
|
||||
private string base64Data = "";
|
||||
|
||||
public Base64Image(Image img, ImageFormat format)
|
||||
{
|
||||
MemoryStream ms = new MemoryStream();
|
||||
img.Save(ms, format);
|
||||
string formatString = ImageCodecInfo.GetImageEncoders().FirstOrDefault(x => x.FormatID == format.Guid).FilenameExtension.Replace("*.", "").ToLower();
|
||||
base64Data = "data:image/" + formatString + ";base64," + Convert.ToBase64String(ms.ToArray());
|
||||
}
|
||||
|
||||
public Image getImage()
|
||||
{
|
||||
string onlyBase64Data = base64Data.Substring(base64Data.IndexOf(";base64,") + (";base64,").Length);
|
||||
byte[] imageData = Convert.FromBase64String(onlyBase64Data);
|
||||
MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length);
|
||||
ms.Write(imageData, 0, imageData.Length);
|
||||
Image image = Image.FromStream(ms, true);
|
||||
return image;
|
||||
}
|
||||
|
||||
public string getImageType()
|
||||
{
|
||||
Match match = Regex.Match(base64Data, "(?<=data:image/)[a-zA-Z]+(?=;base64)");
|
||||
return match.Success ? match.Groups[0].Value : "";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
#region songs
|
||||
|
||||
public delegate SongInfo GetSongDelegate(int songId);
|
||||
|
||||
public delegate SongInfo[] GetAllSongsDelegate();
|
||||
|
||||
public delegate int GetCurrentSongIdDelegate();
|
||||
|
||||
[DataContract]
|
||||
public struct SongInfo
|
||||
{
|
||||
[DataMember]
|
||||
public string Title;
|
||||
[DataMember]
|
||||
public string Artist;
|
||||
[DataMember]
|
||||
public Base64Image Cover;
|
||||
[DataMember]
|
||||
public string Genre { get; set; }
|
||||
[DataMember]
|
||||
public string Language { get; set; }
|
||||
[DataMember]
|
||||
public string Year { get; set; }
|
||||
[DataMember]
|
||||
public bool IsDuet { get; set; }
|
||||
[DataMember]
|
||||
public int SongId { get; set; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,179 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DiffieHellman
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents the Diffie-Hellman algorithm.
|
||||
/// </summary>
|
||||
public class CDiffieHellman : IDisposable
|
||||
{
|
||||
#region - Util -
|
||||
static StrongNumberProvider _strongRng = new StrongNumberProvider();
|
||||
#endregion
|
||||
|
||||
#region - Fields -
|
||||
/// <summary>
|
||||
/// The number of bits to generate.
|
||||
/// </summary>
|
||||
private int bits = 256;
|
||||
|
||||
/// <summary>
|
||||
/// The shared prime.
|
||||
/// </summary>
|
||||
BigInteger prime;
|
||||
/// <summary>
|
||||
/// The shared base.
|
||||
/// </summary>
|
||||
BigInteger g;
|
||||
/// <summary>
|
||||
/// The private prime.
|
||||
/// </summary>
|
||||
BigInteger mine;
|
||||
|
||||
/// <summary>
|
||||
/// The final key.
|
||||
/// </summary>
|
||||
byte[] key;
|
||||
/// <summary>
|
||||
/// The string representation/packet.
|
||||
/// </summary>
|
||||
string representation;
|
||||
#endregion
|
||||
|
||||
#region - Properties -
|
||||
/// <summary>
|
||||
/// Gets the final key to use for encryption.
|
||||
/// </summary>
|
||||
public byte[] Key
|
||||
{
|
||||
get { return key; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region - Ctor -
|
||||
public CDiffieHellman()
|
||||
{
|
||||
}
|
||||
|
||||
public CDiffieHellman(int bits)
|
||||
{
|
||||
this.bits = bits;
|
||||
}
|
||||
|
||||
~CDiffieHellman()
|
||||
{
|
||||
Dispose();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region - Implementation Methods -
|
||||
#region Flow
|
||||
/// <summary>
|
||||
/// Generates a request packet.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public CDiffieHellman GenerateRequest()
|
||||
{
|
||||
// Generate the parameters.
|
||||
prime = BigInteger.GenPseudoPrime(bits, 30, _strongRng);
|
||||
mine = BigInteger.GenPseudoPrime(bits, 30, _strongRng);
|
||||
g = (BigInteger)5;
|
||||
|
||||
// Gemerate the string.
|
||||
StringBuilder rep = new StringBuilder();
|
||||
rep.Append(prime.ToString(36));
|
||||
rep.Append("|");
|
||||
rep.Append(g.ToString(36));
|
||||
rep.Append("|");
|
||||
|
||||
// Generate the send BigInt.
|
||||
using (BigInteger send = g.ModPow(mine, prime))
|
||||
{
|
||||
rep.Append(send.ToString(36));
|
||||
}
|
||||
|
||||
representation = rep.ToString();
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generate a response packet.
|
||||
/// </summary>
|
||||
/// <param name="request">The string representation of the request.</param>
|
||||
/// <returns></returns>
|
||||
public CDiffieHellman GenerateResponse(string request)
|
||||
{
|
||||
string[] parts = request.Split('|');
|
||||
|
||||
// Generate the would-be fields.
|
||||
using (BigInteger prime = new BigInteger(parts[0], 36))
|
||||
using (BigInteger g = new BigInteger(parts[1], 36))
|
||||
using (BigInteger mine = BigInteger.GenPseudoPrime(bits, 30, _strongRng))
|
||||
{
|
||||
// Generate the key.
|
||||
using (BigInteger given = new BigInteger(parts[2], 36))
|
||||
using (BigInteger key = given.ModPow(mine, prime))
|
||||
{
|
||||
this.key = key.GetBytes();
|
||||
}
|
||||
|
||||
// Generate the response.
|
||||
using (BigInteger send = g.ModPow(mine, prime))
|
||||
{
|
||||
this.representation = send.ToString(36);
|
||||
}
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates the key after a response is received.
|
||||
/// </summary>
|
||||
/// <param name="response">The string representation of the response.</param>
|
||||
public void HandleResponse(string response)
|
||||
{
|
||||
// Get the response and modpow it with the stored prime.
|
||||
using (BigInteger given = new BigInteger(response, 36))
|
||||
using (BigInteger key = given.ModPow(mine, prime))
|
||||
{
|
||||
this.key = key.GetBytes();
|
||||
}
|
||||
Dispose();
|
||||
}
|
||||
#endregion
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return representation;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region IDisposable Members
|
||||
/// <summary>
|
||||
/// Ends the calculation. The key will still be available.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (!Object.ReferenceEquals(prime, null))
|
||||
prime.Dispose();
|
||||
if (!Object.ReferenceEquals(mine, null))
|
||||
mine.Dispose();
|
||||
if (!Object.ReferenceEquals(g, null))
|
||||
g.Dispose();
|
||||
|
||||
prime = null;
|
||||
mine = null;
|
||||
g = null;
|
||||
|
||||
representation = null;
|
||||
GC.Collect();
|
||||
GC.Collect();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DiffieHellman
|
||||
{
|
||||
internal class StrongNumberProvider
|
||||
{
|
||||
private static RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider();
|
||||
|
||||
public uint NextUInt32()
|
||||
{
|
||||
byte[] res = new byte[4];
|
||||
csp.GetBytes(res);
|
||||
return BitConverter.ToUInt32(res, 0);
|
||||
}
|
||||
|
||||
public int NextInt()
|
||||
{
|
||||
byte[] res = new byte[4];
|
||||
csp.GetBytes(res);
|
||||
return BitConverter.ToInt32(res, 0);
|
||||
}
|
||||
|
||||
public Single NextSingle()
|
||||
{
|
||||
float numerator = NextUInt32();
|
||||
float denominator = uint.MaxValue;
|
||||
return numerator / denominator;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-7
@@ -8,7 +8,7 @@
|
||||
<ProjectGuid>{EC5167E4-CCFB-4CEE-987C-CF816F1062A3}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>ClientServerLib</RootNamespace>
|
||||
<RootNamespace>ServerLib</RootNamespace>
|
||||
<AssemblyName>ClientServerLib</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
@@ -47,17 +47,11 @@
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="CClient.cs" />
|
||||
<Compile Include="CConnection.cs" />
|
||||
<Compile Include="CDiscover.cs" />
|
||||
<Compile Include="CServer.cs" />
|
||||
<Compile Include="CWebservice.cs" />
|
||||
<Compile Include="DataStructs.cs" />
|
||||
<Compile Include="DeffieHellman\BigInt.cs" />
|
||||
<Compile Include="DeffieHellman\DeffieHellman.cs" />
|
||||
<Compile Include="DeffieHellman\StrongNumberProvider.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="Structs.cs" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
@@ -1,21 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace ClientServerLib
|
||||
{
|
||||
public delegate void ResponseCallback(byte[] Response);
|
||||
public delegate byte[] HandleRequest(int ConnectionID, byte[] Message);
|
||||
|
||||
public delegate void OnConnectionChanged(bool Connected);
|
||||
public delegate void OnSend(byte[] Message);
|
||||
public delegate void OnReceived(byte[] Message);
|
||||
|
||||
public struct SRequest
|
||||
{
|
||||
public byte[] Command;
|
||||
public byte[] Response;
|
||||
public ResponseCallback Callback;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user