WCF-Server inital commit (Wenserver without usermanagement and with some pages)

This commit is contained in:
lukeIam committed 2013-12-13 17:34:07 +01:00
1 parent 2f6002e932
commit 28da5b776f
31 files changed
+1371 -438

No files matched your search

+111 -194
View File
@@ -1,194 +1,111 @@
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 CServer
{
private TcpListener tcpListener;
private Thread listenThread;
private int port;
private bool encryption;
private string password;
private int bufferLength = 8192;
private bool running;
private HandleRequest requestCallback;
private Dictionary<int, CConnection> clients;
private Queue<int> ids;
public CServer(HandleRequest RequestCallback, int Port = 3000, string Password = null)
{
port = Port;
running = false;
requestCallback = RequestCallback;
encryption = Password != null;
password = Password;
clients = new Dictionary<int, CConnection>();
ids = new Queue<int>(1000);
for (int i = 0; i < 1000; i++)
ids.Enqueue(i);
}
public void Start()
{
if (!running)
{
running = true;
tcpListener = new TcpListener(IPAddress.Any, port);
listenThread = new Thread(new ThreadStart(ListenForClients));
listenThread.Start();
}
}
public void Stop()
{
if (running)
{
running = false;
tcpListener.Stop();
Thread.Sleep(100);
listenThread.Join();
lock (clients)
{
int[] cIDs = new int[clients.Count];
clients.Keys.CopyTo(cIDs, 0);
foreach (int id in cIDs)
{
clients.Remove(id);
ids.Enqueue(id);
}
}
}
}
private void ListenForClients()
{
tcpListener.Start();
TcpClient client;
while (running)
{
//wait for new client
try
{
client = tcpListener.AcceptTcpClient();
}
catch
{
client = null;
}
if (client != null)
{
int id = ids.Dequeue();
CConnection connection = new CConnection(client, id, password);
lock (clients)
{
clients.Add(id, connection);
}
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientCom));
NetworkStream clientStream = client.GetStream();
byte[] serverParams = connection.GetKeyParams();
try
{
clientStream.Write(serverParams, 0, serverParams.Length);
clientStream.Flush();
}
catch
{
client = null;
}
if (client != null)
clientThread.Start(connection);
}
}
}
private void HandleClientCom(object client)
{
CConnection connection = (CConnection)client;
TcpClient tcpClient = (TcpClient)connection.TcpClient;
NetworkStream clientStream = tcpClient.GetStream();
byte[] data = new byte[bufferLength];
int bytesRead;
while (running)
{
bytesRead = 0;
try
{
bytesRead = clientStream.Read(data, 0, bufferLength);
}
catch
{
break;
}
if (bytesRead == 0)
break;
if (!connection.KeySet)
{
byte[] clientResponse = new byte[bytesRead];
Array.Copy(data, clientResponse, bytesRead);
connection.CreateServerKey(clientResponse);
}
else
{
//receive message
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);
}
byte[] message = new byte[bytesRead];
Array.Copy(data, message, bytesRead);
byte[] decrypted = connection.Decrypt(message);
byte[] answer = HandleClientMessage(decrypted, connection);
//send message
byte[] encrypted = connection.Encrypt(answer);
try
{
clientStream.Write(encrypted, 0, encrypted.Length);
clientStream.Flush();
}
catch
{
break;
}
}
}
}
private byte[] HandleClientMessage(byte[] Message, CConnection connection)
{
return requestCallback(connection.ConnectionID, Message);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
namespace ClientServerLib
{
public class CServer
{
private ServiceHost host;
private Uri baseAddress;
private static SendKeyEventDelegate sendKeyEvent;
public static SendKeyEventDelegate SendKeyEvent
{
internal get { return CServer.sendKeyEvent; }
set { CServer.sendKeyEvent = value; }
}
#region profile
private static GetProfileDataDelegate getProfileData;
public static GetProfileDataDelegate GetProfileData
{
internal get { return CServer.getProfileData; }
set { CServer.getProfileData = value; }
}
private static SendProfileDataDelegate sendProfileData;
public static SendProfileDataDelegate SendProfileData
{
internal get { return CServer.sendProfileData; }
set { CServer.sendProfileData = value; }
}
private static GetProfileListDelegate getProfileList;
public static GetProfileListDelegate GetProfileList
{
internal get { return CServer.getProfileList; }
set { CServer.getProfileList = value; }
}
#endregion
#region photo
private static SendPhotoDelegate sendPhoto;
public static SendPhotoDelegate SendPhoto
{
get { return CServer.sendPhoto; }
set { CServer.sendPhoto = value; }
}
#endregion
#region website
private static GetSiteFileDelegate getSiteFile;
public static GetSiteFileDelegate GetSiteFile
{
internal get { return CServer.getSiteFile; }
set { CServer.getSiteFile = value; }
}
#endregion
public CServer(int port)
{
baseAddress = new Uri("http://localhost:" + port + "/");
host = new WebServiceHost(typeof(CWebservice), baseAddress);
WebHttpBinding wb = new WebHttpBinding();
wb.MaxReceivedMessageSize = 10485760;
wb.MaxBufferSize = 10485760;
host.AddServiceEndpoint(typeof(ICWebservice), wb, "Vocaluxe");
}
public void Start()
{
try
{
// Step 4 Enable metadata exchange.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb);
// Step 5 Start the service.
host.Open();
}
catch (CommunicationException ce)
{
host.Abort();
}
}
public void Stop()
{
try
{
host.Close();
}
catch (CommunicationException ce)
{
host.Abort();
}
}
}
}
@@ -0,0 +1,239 @@
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(Name = "Vocaluxe")]
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",
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
}
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
}
}
@@ -1,61 +1,70 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{EC5167E4-CCFB-4CEE-987C-CF816F1062A3}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ClientServerLib</RootNamespace>
<AssemblyName>ClientServerLib</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CClient.cs" />
<Compile Include="CConnection.cs" />
<Compile Include="CDiscover.cs" />
<Compile Include="CServer.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" />
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{EC5167E4-CCFB-4CEE-987C-CF816F1062A3}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ClientServerLib</RootNamespace>
<AssemblyName>ClientServerLib</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.ServiceModel.Web" />
<Reference Include="System.Web.Services" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<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.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
-->
</Project>
@@ -0,0 +1,92 @@
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()
{
byte[] imageData = Convert.FromBase64String(base64Data);
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[1].Value : "";
}
}
}