some modifications for ClientServerLib

This commit is contained in:
Alexander Eckart committed 2013-06-09 12:52:26 +02:00
1 parent ca5fc16332
commit 214cd0f661
17 files changed
+322 -222

No files matched your search

@@ -36,8 +36,8 @@
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<AndroidUseSharedRuntime>false</AndroidUseSharedRuntime> <AndroidUseSharedRuntime>false</AndroidUseSharedRuntime>
<ConsolePause>false</ConsolePause> <ConsolePause>false</ConsolePause>
<AndroidLinkMode>SdkOnly</AndroidLinkMode>
<DefineConstants>MONO</DefineConstants> <DefineConstants>MONO</DefineConstants>
<EmbedAssembliesIntoApk>true</EmbedAssembliesIntoApk>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
@@ -96,4 +96,68 @@
<Folder Include="ClientServerLib\Vocaluxe\" /> <Folder Include="ClientServerLib\Vocaluxe\" />
<Folder Include="ClientServerLib\Server\" /> <Folder Include="ClientServerLib\Server\" />
</ItemGroup> </ItemGroup>
<ProjectExtensions>
<MonoDevelop>
<Properties>
<Policies>
<TextStylePolicy TabsToSpaces="False" inheritsSet="VisualStudio" inheritsScope="text/plain" scope="text/plain" />
<NameConventionPolicy>
<Rules>
<NamingRule Name="Namespaces" AffectedEntity="Namespace" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
<NamingRule Name="Types" AffectedEntity="Class, Struct, Enum, Delegate" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
<NamingRule Name="Interfaces" AffectedEntity="Interface" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True">
<RequiredPrefixes>
<String>I</String>
</RequiredPrefixes>
</NamingRule>
<NamingRule Name="Attributes" AffectedEntity="CustomAttributes" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True">
<RequiredSuffixes>
<String>Attribute</String>
</RequiredSuffixes>
</NamingRule>
<NamingRule Name="Event Arguments" AffectedEntity="CustomEventArgs" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True">
<RequiredSuffixes>
<String>EventArgs</String>
</RequiredSuffixes>
</NamingRule>
<NamingRule Name="Exceptions" AffectedEntity="CustomExceptions" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True">
<RequiredSuffixes>
<String>Exception</String>
</RequiredSuffixes>
</NamingRule>
<NamingRule Name="Methods" AffectedEntity="Methods" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
<NamingRule Name="Static Readonly Fields" AffectedEntity="ReadonlyField" VisibilityMask="Internal, Protected, Public" NamingStyle="PascalCase" IncludeInstanceMembers="False" IncludeStaticEntities="True" />
<NamingRule Name="Fields (Non Private)" AffectedEntity="Field" VisibilityMask="Internal, Protected, Public" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
<NamingRule Name="ReadOnly Fields (Non Private)" AffectedEntity="ReadonlyField" VisibilityMask="Internal, Protected, Public" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="False" />
<NamingRule Name="Fields (Private)" AffectedEntity="Field, ReadonlyField" VisibilityMask="Private" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="False">
<AllowedPrefixes>
<String>_</String>
<String>m_</String>
</AllowedPrefixes>
</NamingRule>
<NamingRule Name="Static Fields (Private)" AffectedEntity="Field" VisibilityMask="Private" NamingStyle="CamelCase" IncludeInstanceMembers="False" IncludeStaticEntities="True" />
<NamingRule Name="ReadOnly Fields (Private)" AffectedEntity="ReadonlyField" VisibilityMask="Private" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="False">
<AllowedPrefixes>
<String>_</String>
<String>m_</String>
</AllowedPrefixes>
</NamingRule>
<NamingRule Name="Constant Fields" AffectedEntity="ConstantField" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
<NamingRule Name="Properties" AffectedEntity="Property" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
<NamingRule Name="Events" AffectedEntity="Event" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
<NamingRule Name="Enum Members" AffectedEntity="EnumMember" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
<NamingRule Name="Parameters" AffectedEntity="Parameter" VisibilityMask="VisibilityMask" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
<NamingRule Name="Type Parameters" AffectedEntity="TypeParameter" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True">
<RequiredPrefixes>
<String>T</String>
</RequiredPrefixes>
</NamingRule>
</Rules>
</NameConventionPolicy>
<VersionControlPolicy inheritsSet="Mono" />
<ChangeLogPolicy inheritsSet="Mono" />
</Policies>
</Properties>
</MonoDevelop>
</ProjectExtensions>
</Project> </Project>
+33 -43
View File
@@ -16,12 +16,12 @@ using Vocaluxe.Base.Server;
namespace AndroidRemote namespace AndroidRemote
{ {
[Activity (Label = "Vocaluxe Remote", MainLauncher = true, ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation)] [Activity (Label = "Vocaluxe App", MainLauncher = true, ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation)]
public class Activity1 : Activity public class Activity1 : Activity
{ {
CClient client = new CClient(); CClient client = new CClient();
CDiscover discover;
Button bConnect; Button bConnect;
Button bLogin;
Button bSendAvatar; Button bSendAvatar;
Button bSendProfile; Button bSendProfile;
@@ -48,9 +48,9 @@ namespace AndroidRemote
bConnect = FindViewById<Button> (Resource.Id.btConnect); bConnect = FindViewById<Button> (Resource.Id.btConnect);
bConnect.Click += delegate { Connect(); }; bConnect.Click += delegate { Connect(); };
bLogin = FindViewById<Button> (Resource.Id.btLogin); Button bDiscover = FindViewById<Button> (Resource.Id.btDiscover);
bLogin.Click += delegate { Login(); }; bDiscover.Click += delegate { Discover(); };
bSendAvatar = FindViewById<Button> (Resource.Id.btSendAvatar); bSendAvatar = FindViewById<Button> (Resource.Id.btSendAvatar);
bSendAvatar.Click += SendAvatar; bSendAvatar.Click += SendAvatar;
@@ -62,6 +62,9 @@ namespace AndroidRemote
tPassword = FindViewById<TextView> (Resource.Id.tbPassword); tPassword = FindViewById<TextView> (Resource.Id.tbPassword);
sendProfile = false; sendProfile = false;
discover = new CDiscover(3000, CCommands.BroadcastKeyword);
Discover ();
} }
protected override void OnStop () protected override void OnStop ()
@@ -120,8 +123,8 @@ namespace AndroidRemote
return; return;
Intent intent = new Intent(MediaStore.ActionImageCapture); Intent intent = new Intent(MediaStore.ActionImageCapture);
dir = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures), "AndroidRemote"); dir = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures), Resources.GetString(Resource.String.app_name));
if (dir.Exists()) if (!dir.Exists())
{ {
dir.Mkdirs(); dir.Mkdirs();
} }
@@ -140,10 +143,15 @@ namespace AndroidRemote
private void Connect() private void Connect()
{ {
if (!client.Connected) if (!client.Connected)
client.Connect(tIP.Text, 3000, OnConnectionChanged); client.Connect(tIP.Text, 3000, tPassword.Text, OnConnectionChanged);
else else
client.Disconnect(); client.Disconnect();
} }
private void Discover()
{
discover.Discover (_OnDiscovered);
}
private void Login() private void Login()
{ {
@@ -169,18 +177,6 @@ namespace AndroidRemote
int command = BitConverter.ToInt32(Message, 0); int command = BitConverter.ToInt32(Message, 0);
switch (command) switch (command)
{ {
case CCommands.ResponseLoginFailed:
RunOnUiThread (() => Toast.MakeText(this, Resources.GetString(Resource.String.message_login_failed), ToastLength.Short).Show());
break;
case CCommands.ResponseLoginWrongPassword:
RunOnUiThread (() => Toast.MakeText(this, Resources.GetString(Resource.String.message_wrong_password), ToastLength.Short).Show());
break;
case CCommands.ResponseLoginOK:
RunOnUiThread (() => UpdateLoginStatus(true));
break;
case CCommands.ResponseOK: case CCommands.ResponseOK:
RunOnUiThread (() => Toast.MakeText(this, Resources.GetString(Resource.String.message_ok), ToastLength.Short).Show()); RunOnUiThread (() => Toast.MakeText(this, Resources.GetString(Resource.String.message_ok), ToastLength.Short).Show());
break; break;
@@ -194,42 +190,36 @@ namespace AndroidRemote
} }
} }
private void _OnDiscovered(string Address, string HostName)
{
RunOnUiThread (() =>
{
if (Address != "Timeout")
{
tIP.Text = Address;
Connect ();
}
else
Toast.MakeText(this, "Cant't find any Vocaluxe Server", ToastLength.Short).Show();
});
}
private void UpdateConnectionStatus(bool Connected) private void UpdateConnectionStatus(bool Connected)
{ {
if (Connected) if (Connected)
{ {
bLogin.Enabled = true;
bConnect.Text = Resources.GetString(Resource.String.button_disconnect); bConnect.Text = Resources.GetString(Resource.String.button_disconnect);
Toast.MakeText(this, Resource.String.message_connected, ToastLength.Short).Show(); Toast.MakeText(this, Resource.String.message_connected, ToastLength.Short).Show();
}
else
{
client.Disconnect();
bLogin.Enabled = false;
bLogin.Text = Resources.GetString(Resource.String.button_login);
bConnect.Text = Resources.GetString(Resource.String.button_connect);
bSendAvatar.Enabled = false;
bSendProfile.Enabled = false;
Toast.MakeText(this, Resources.GetString(Resource.String.message_disconnected), ToastLength.Short).Show();
}
}
private void UpdateLoginStatus(bool LoggedIn)
{
loggedIn = LoggedIn;
if (LoggedIn)
{
bLogin.Text = Resources.GetString(Resource.String.button_logout);
Toast.MakeText(this, Resources.GetString(Resource.String.message_logged_in), ToastLength.Short).Show();
bSendAvatar.Enabled = true; bSendAvatar.Enabled = true;
bSendProfile.Enabled = true; bSendProfile.Enabled = true;
} }
else else
{ {
Toast.MakeText(this, Resources.GetString(Resource.String.message_logged_out), ToastLength.Short).Show(); client.Disconnect();
bConnect.Text = Resources.GetString(Resource.String.button_connect);
bSendAvatar.Enabled = false; bSendAvatar.Enabled = false;
bSendProfile.Enabled = false; bSendProfile.Enabled = false;
Toast.MakeText(this, Resources.GetString(Resource.String.message_disconnected), ToastLength.Short).Show();
} }
} }
} }
@@ -4,4 +4,5 @@
<application android:label="AndroidRemote" android:icon="@drawable/icon"></application> <application android:label="AndroidRemote" android:icon="@drawable/icon"></application>
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest> </manifest>
+44 -84
View File
@@ -2,7 +2,7 @@
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// <auto-generated> // <auto-generated>
// Dieser Code wurde von einem Tool generiert. // Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.18034 // Laufzeitversion:4.0.30319.18047
// //
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird. // der Code erneut generiert wird.
@@ -47,9 +47,6 @@ namespace AndroidRemote
// aapt resource value: 0x7f020000 // aapt resource value: 0x7f020000
public const int Icon = 2130837504; public const int Icon = 2130837504;
// aapt resource value: 0x7f020001
public const int monoandroidsplash = 2130837505;
static Drawable() static Drawable()
{ {
global::Android.Runtime.ResourceIdManager.UpdateIdValues(); global::Android.Runtime.ResourceIdManager.UpdateIdValues();
@@ -63,35 +60,35 @@ namespace AndroidRemote
public partial class Id public partial class Id
{ {
// aapt resource value: 0x7f060002 // aapt resource value: 0x7f050004
public const int btConnect = 2131099650; public const int btConnect = 2131034116;
// aapt resource value: 0x7f060005 // aapt resource value: 0x7f050005
public const int btLogin = 2131099653; public const int btDiscover = 2131034117;
// aapt resource value: 0x7f060006 // aapt resource value: 0x7f050006
public const int btSendAvatar = 2131099654; public const int btSendAvatar = 2131034118;
// aapt resource value: 0x7f060009 // aapt resource value: 0x7f050009
public const int btSendProfile = 2131099657; public const int btSendProfile = 2131034121;
// aapt resource value: 0x7f060001 // aapt resource value: 0x7f050001
public const int tbIP = 2131099649; public const int tbIP = 2131034113;
// aapt resource value: 0x7f060004 // aapt resource value: 0x7f050003
public const int tbPassword = 2131099652; public const int tbPassword = 2131034115;
// aapt resource value: 0x7f060008 // aapt resource value: 0x7f050008
public const int tbPlayerName = 2131099656; public const int tbPlayerName = 2131034120;
// aapt resource value: 0x7f060000 // aapt resource value: 0x7f050000
public const int textView1 = 2131099648; public const int textView1 = 2131034112;
// aapt resource value: 0x7f060003 // aapt resource value: 0x7f050002
public const int textView2 = 2131099651; public const int textView2 = 2131034114;
// aapt resource value: 0x7f060007 // aapt resource value: 0x7f050007
public const int textView3 = 2131099655; public const int textView3 = 2131034119;
static Id() static Id()
{ {
@@ -109,9 +106,6 @@ namespace AndroidRemote
// aapt resource value: 0x7f030000 // aapt resource value: 0x7f030000
public const int Main = 2130903040; public const int Main = 2130903040;
// aapt resource value: 0x7f030001
public const int monoandroidsplash = 2130903041;
static Layout() static Layout()
{ {
global::Android.Runtime.ResourceIdManager.UpdateIdValues(); global::Android.Runtime.ResourceIdManager.UpdateIdValues();
@@ -135,55 +129,37 @@ namespace AndroidRemote
public const int button_disconnect = 2130968578; public const int button_disconnect = 2130968578;
// aapt resource value: 0x7f040003 // aapt resource value: 0x7f040003
public const int button_login = 2130968579; public const int button_send_avatar = 2130968579;
// aapt resource value: 0x7f040004 // aapt resource value: 0x7f040004
public const int button_logout = 2130968580; public const int button_send_profile = 2130968580;
// aapt resource value: 0x7f040005
public const int button_send_avatar = 2130968581;
// aapt resource value: 0x7f040006
public const int button_send_profile = 2130968582;
// aapt resource value: 0x7f040012
public const int ip_address = 2130968594;
// aapt resource value: 0x7f040007
public const int message_connected = 2130968583;
// aapt resource value: 0x7f040008
public const int message_disconnected = 2130968584;
// aapt resource value: 0x7f040009
public const int message_logged_in = 2130968585;
// aapt resource value: 0x7f04000a
public const int message_logged_out = 2130968586;
// aapt resource value: 0x7f04000b
public const int message_login_failed = 2130968587;
// aapt resource value: 0x7f04000e
public const int message_nok = 2130968590;
// aapt resource value: 0x7f04000d
public const int message_ok = 2130968589;
// aapt resource value: 0x7f04000c // aapt resource value: 0x7f04000c
public const int message_wrong_password = 2130968588; public const int ip_address = 2130968588;
// aapt resource value: 0x7f040013 // aapt resource value: 0x7f040005
public const int password = 2130968595; public const int message_connected = 2130968581;
// aapt resource value: 0x7f04000f // aapt resource value: 0x7f040006
public const int text_ip_address = 2130968591; public const int message_disconnected = 2130968582;
// aapt resource value: 0x7f040010 // aapt resource value: 0x7f040008
public const int text_password = 2130968592; public const int message_nok = 2130968584;
// aapt resource value: 0x7f040011 // aapt resource value: 0x7f040007
public const int text_player_name = 2130968593; public const int message_ok = 2130968583;
// aapt resource value: 0x7f04000d
public const int password = 2130968589;
// aapt resource value: 0x7f040009
public const int text_ip_address = 2130968585;
// aapt resource value: 0x7f04000a
public const int text_password = 2130968586;
// aapt resource value: 0x7f04000b
public const int text_player_name = 2130968587;
static String() static String()
{ {
@@ -194,22 +170,6 @@ namespace AndroidRemote
{ {
} }
} }
public partial class Style
{
// aapt resource value: 0x7f050000
public const int Mono_Android_Theme_Splash = 2131034112;
static Style()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Style()
{
}
}
} }
} }
#pragma warning restore 1591 #pragma warning restore 1591
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

After

Width:  |  Height:  |  Size: 60 KiB

@@ -15,11 +15,6 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:id="@+id/tbIP" android:id="@+id/tbIP"
android:text="@string/ip_address" /> android:text="@string/ip_address" />
<Button
android:text="@string/button_connect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/btConnect" />
<TextView <TextView
android:text="@string/text_password" android:text="@string/text_password"
android:textAppearance="?android:attr/textAppearanceMedium" android:textAppearance="?android:attr/textAppearanceMedium"
@@ -32,11 +27,15 @@
android:id="@+id/tbPassword" android:id="@+id/tbPassword"
android:text="@string/password" /> android:text="@string/password" />
<Button <Button
android:text="@string/button_login" android:text="@string/button_connect"
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:id="@+id/btLogin" android:id="@+id/btConnect" />
android:enabled="false" /> <Button
android:text="Discover"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/btDiscover" />
<Button <Button
android:text="@string/button_send_avatar" android:text="@string/button_send_avatar"
android:layout_width="fill_parent" android:layout_width="fill_parent"
@@ -1,23 +1,17 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<string name="app_name">AndroidRemote</string> <string name="app_name">Vocaluxe App</string>
<string name="button_connect">Connect</string> <string name="button_connect">Connect</string>
<string name="button_disconnect">Disconnect</string> <string name="button_disconnect">Disconnect</string>
<string name="button_login">Login</string>
<string name="button_logout">Logout</string>
<string name="button_send_avatar">Send Avatar Picture</string> <string name="button_send_avatar">Send Avatar Picture</string>
<string name="button_send_profile">Send Profile</string> <string name="button_send_profile">Send Profile</string>
<string name="message_connected">Connected</string> <string name="message_connected">Connected</string>
<string name="message_disconnected">Disconnected</string> <string name="message_disconnected">Disconnected</string>
<string name="message_logged_in">Logged in</string>
<string name="message_logged_out">Logged out</string>
<string name="message_login_failed">Login failed</string>
<string name="message_wrong_password">Wrong Password</string>
<string name="message_ok">Success</string> <string name="message_ok">Success</string>
<string name="message_nok">Error</string> <string name="message_nok">Error</string>
<string name="text_ip_address">IP Address of Vocaluxe Server:</string> <string name="text_ip_address">IP Address of Vocaluxe Server:</string>
<string name="text_password">Password:</string> <string name="text_password">Password:</string>
<string name="text_player_name">Player Name:</string> <string name="text_player_name">Player Name:</string>
<string name="ip_address">192.168.178.57</string> <string name="ip_address"></string>
<string name="password">vocaluxe</string> <string name="password">vocaluxe</string>
</resources> </resources>
+87 -14
View File
@@ -29,6 +29,8 @@ namespace ClientServerLib
private OnSend onSend; private OnSend onSend;
private OnReceived onReceived; private OnReceived onReceived;
private byte[] data;
public bool Connected public bool Connected
{ {
get { return connected; } get { return connected; }
@@ -41,14 +43,12 @@ namespace ClientServerLib
running = true; running = true;
requests = new List<SRequest>(); requests = new List<SRequest>();
responses = new List<SRequest>(); responses = new List<SRequest>();
data = new byte[bufferLength];
connection = new CConnection(new TcpClient(), -1); connection = new CConnection(new TcpClient(), -1);
clientThread = new Thread(new ThreadStart(Runner));
clientThread.Start();
} }
public void Connect(string IP = "127.0.0.1", int Port = 3000, public void Connect(string IP = "127.0.0.1", int Port = 3000, string Password = null,
OnConnectionChanged OnConnectionChanged = null, OnConnectionChanged OnConnectionChanged = null,
OnSend OnSend = null, OnSend OnSend = null,
OnReceived OnReceived = null) OnReceived OnReceived = null)
@@ -61,7 +61,15 @@ namespace ClientServerLib
ip = IP; ip = IP;
port = Port; port = Port;
connection.Password = Password;
doConnect = true; doConnect = true;
if (clientThread == null)
{
running = true;
clientThread = new Thread(new ThreadStart(Runner));
clientThread.Start();
}
} }
} }
@@ -85,9 +93,13 @@ namespace ClientServerLib
public void Close() public void Close()
{ {
Disconnect();
running = false; running = false;
clientThread.Join(100);
if (clientThread != null)
clientThread.Join(100);
clientThread = null;
DoDisconnect();
} }
public void SendMessage(byte[] Message, ResponseCallback Callback) public void SendMessage(byte[] Message, ResponseCallback Callback)
@@ -111,10 +123,14 @@ namespace ClientServerLib
{ {
try try
{ {
serverEndPoint = new IPEndPoint(IPAddress.Parse(ip), port); IPAddress resolvedIP;
connection.TcpClient.Connect(serverEndPoint); if (TryResolveIPAddress(ip, out resolvedIP))
connected = true; {
RaiseOnConnectionChanged(); serverEndPoint = new IPEndPoint(resolvedIP, port);
connection.TcpClient.Connect(serverEndPoint);
connected = true;
RaiseOnConnectionChanged();
}
} }
catch catch
{ {
@@ -122,7 +138,7 @@ namespace ClientServerLib
for (int i = 0; i < 500; i++) for (int i = 0; i < 500; i++)
{ {
if (doConnect) if (running && doConnect)
Thread.Sleep(10); Thread.Sleep(10);
else else
break; break;
@@ -141,6 +157,7 @@ namespace ClientServerLib
try try
{ {
Communicate(); Communicate();
Thread.Sleep(10);
} }
catch catch
{ {
@@ -148,9 +165,62 @@ namespace ClientServerLib
} }
} }
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() private void DoDisconnect()
{ {
try try
@@ -161,6 +231,7 @@ namespace ClientServerLib
connection = new CConnection(new TcpClient(), -1); connection = new CConnection(new TcpClient(), -1);
connected = false; connected = false;
doConnect = false;
RaiseOnConnectionChanged(); RaiseOnConnectionChanged();
} }
@@ -170,8 +241,7 @@ namespace ClientServerLib
DoDisconnect(); DoDisconnect();
NetworkStream clientStream = connection.TcpClient.GetStream(); NetworkStream clientStream = connection.TcpClient.GetStream();
byte[] data = new byte[bufferLength];
int bytesRead; int bytesRead;
if (!connection.KeySet) if (!connection.KeySet)
@@ -302,7 +372,10 @@ namespace ClientServerLib
{ {
onConnectionChanged(connected); onConnectionChanged(connected);
} }
catch {} catch (Exception e)
{
Console.WriteLine (e.Message);
}
} }
private void RaiseOnSend(byte[] Message) private void RaiseOnSend(byte[] Message)
+37 -6
View File
@@ -14,10 +14,13 @@ namespace ClientServerLib
internal class CConnection internal class CConnection
{ {
private bool keySet; private bool keySet;
private byte[] key;
private bool encryption; private bool encryption;
private CDiffieHellman dh; private string password;
private CDiffieHellman dh;
private UTF8Encoding encoder; private UTF8Encoding encoder;
private int connectionID; private int connectionID;
private static SHA256Managed SHA256 = new SHA256Managed();
public TcpClient TcpClient; public TcpClient TcpClient;
@@ -31,14 +34,26 @@ namespace ClientServerLib
get { return connectionID; } get { return connectionID; }
} }
public CConnection(TcpClient client, int ConnectionID, bool Encryption = false) public string Password
{
set
{
password = value;
encryption = value != null;
keySet = false;
}
}
public CConnection(TcpClient client, int ConnectionID, string Password = null)
{ {
TcpClient = client; TcpClient = client;
client.NoDelay = true; client.NoDelay = true;
keySet = false; keySet = false;
encryption = Encryption; encryption = Password != null;
password = Password;
connectionID = ConnectionID; connectionID = ConnectionID;
encoder = new UTF8Encoding(); encoder = new UTF8Encoding();
key = null;
} }
public byte[] GetKeyParams() public byte[] GetKeyParams()
@@ -64,11 +79,12 @@ namespace ClientServerLib
{ {
encryption = false; encryption = false;
keySet = true; keySet = true;
key = null;
return encoder.GetBytes(response); return encoder.GetBytes(response);
} }
dh = new CDiffieHellman(256).GenerateResponse(response); dh = new CDiffieHellman(256).GenerateResponse(response);
key = _BuildHash(dh.Key, password);
keySet = true; keySet = true;
encryption = true; encryption = true;
return encoder.GetBytes(dh.ToString()); return encoder.GetBytes(dh.ToString());
@@ -81,6 +97,7 @@ namespace ClientServerLib
if (response == "NO ENCRYPTION") if (response == "NO ENCRYPTION")
{ {
keySet = true; keySet = true;
key = null;
return; return;
} }
@@ -88,6 +105,7 @@ namespace ClientServerLib
return; return;
dh.HandleResponse(response); dh.HandleResponse(response);
key = _BuildHash(dh.Key, password);
keySet = true; keySet = true;
} }
@@ -101,6 +119,19 @@ namespace ClientServerLib
return _Decompress(_Decrypt(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) private byte[] _Encrypt(byte[] Data)
{ {
if (Data == null || (!keySet && encryption)) if (Data == null || (!keySet && encryption))
@@ -125,7 +156,7 @@ namespace ClientServerLib
using (Aes aes = new AesManaged()) using (Aes aes = new AesManaged())
{ {
aes.Key = dh.Key; aes.Key = key;
aes.GenerateIV(); aes.GenerateIV();
using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV)) using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
@@ -184,7 +215,7 @@ namespace ClientServerLib
using (Aes aes = new AesManaged()) using (Aes aes = new AesManaged())
{ {
aes.Key = dh.Key; aes.Key = key;
aes.IV = IV; aes.IV = IV;
byte[] encrypted = new byte[messageLength - 24]; byte[] encrypted = new byte[messageLength - 24];
+6 -1
View File
@@ -14,6 +14,9 @@ namespace ClientServerLib
public class CDiscover public class CDiscover
{ {
public readonly string sTimeout = "Timeout";
public readonly string sFinished = "Finished";
private string _Keyword; private string _Keyword;
private string _BroadcastAddress; private string _BroadcastAddress;
private int _Port; private int _Port;
@@ -114,7 +117,9 @@ namespace ClientServerLib
_DiscoverRunning = false; _DiscoverRunning = false;
if (!foundSomething) if (!foundSomething)
_OnDiscovered("Timeout", "unknown"); _OnDiscovered(sTimeout, String.Empty);
else
_OnDiscovered(sFinished, String.Empty);
} }
} }
} }
+26 -8
View File
@@ -14,6 +14,7 @@ namespace ClientServerLib
private Thread listenThread; private Thread listenThread;
private int port; private int port;
private bool encryption; private bool encryption;
private string password;
private int bufferLength = 8192; private int bufferLength = 8192;
private bool running; private bool running;
@@ -22,12 +23,13 @@ namespace ClientServerLib
private Dictionary<int, CConnection> clients; private Dictionary<int, CConnection> clients;
private Queue<int> ids; private Queue<int> ids;
public CServer(HandleRequest RequestCallback, int Port = 3000, bool Encryption = false) public CServer(HandleRequest RequestCallback, int Port = 3000, string Password = null)
{ {
port = Port; port = Port;
running = false; running = false;
requestCallback = RequestCallback; requestCallback = RequestCallback;
encryption = Encryption; encryption = Password != null;
password = Password;
clients = new Dictionary<int, CConnection>(); clients = new Dictionary<int, CConnection>();
ids = new Queue<int>(1000); ids = new Queue<int>(1000);
@@ -92,7 +94,7 @@ namespace ClientServerLib
if (client != null) if (client != null)
{ {
int id = ids.Dequeue(); int id = ids.Dequeue();
CConnection connection = new CConnection(client, id, encryption); CConnection connection = new CConnection(client, id, password);
lock (clients) lock (clients)
{ {
@@ -103,10 +105,19 @@ namespace ClientServerLib
NetworkStream clientStream = client.GetStream(); NetworkStream clientStream = client.GetStream();
byte[] serverParams = connection.GetKeyParams(); byte[] serverParams = connection.GetKeyParams();
clientStream.Write(serverParams, 0, serverParams.Length);
clientStream.Flush();
clientThread.Start(connection); try
{
clientStream.Write(serverParams, 0, serverParams.Length);
clientStream.Flush();
}
catch
{
client = null;
}
if (client != null)
clientThread.Start(connection);
} }
} }
} }
@@ -162,8 +173,15 @@ namespace ClientServerLib
//send message //send message
byte[] encrypted = connection.Encrypt(answer); byte[] encrypted = connection.Encrypt(answer);
clientStream.Write(encrypted, 0, encrypted.Length); try
clientStream.Flush(); {
clientStream.Write(encrypted, 0, encrypted.Length);
clientStream.Flush();
}
catch
{
break;
}
} }
} }
} }
@@ -971,6 +971,9 @@ namespace DiffieHellman
public override bool Equals(object o) public override bool Equals(object o)
{ {
if (o == null)
return false;
BigInteger bi = (BigInteger)o; BigInteger bi = (BigInteger)o;
if (this.dataLength != bi.dataLength) if (this.dataLength != bi.dataLength)
@@ -2965,8 +2968,6 @@ namespace DiffieHellman
{ {
data = new uint[0]; data = new uint[0];
data = null; data = null;
GC.Collect();
GC.Collect();
} }
#endregion #endregion
@@ -115,10 +115,11 @@ namespace DiffieHellman
{ {
// Generate the key. // Generate the key.
using (BigInteger given = new BigInteger(parts[2], 36)) using (BigInteger given = new BigInteger(parts[2], 36))
using (BigInteger key = given.ModPow(mine, prime)) using (BigInteger key = given.ModPow(mine, prime))
{ {
this.key = key.GetBytes(); this.key = key.GetBytes();
} }
// Generate the response. // Generate the response.
using (BigInteger send = g.ModPow(mine, prime)) using (BigInteger send = g.ModPow(mine, prime))
{ {
+3 -17
View File
@@ -42,7 +42,6 @@
this.lbServerIP = new System.Windows.Forms.Label(); this.lbServerIP = new System.Windows.Forms.Label();
this.tbPassword = new System.Windows.Forms.TextBox(); this.tbPassword = new System.Windows.Forms.TextBox();
this.lbPassword = new System.Windows.Forms.Label(); this.lbPassword = new System.Windows.Forms.Label();
this.btLogin = new System.Windows.Forms.Button();
this.btLeft = new System.Windows.Forms.Button(); this.btLeft = new System.Windows.Forms.Button();
this.btRight = new System.Windows.Forms.Button(); this.btRight = new System.Windows.Forms.Button();
this.btUp = new System.Windows.Forms.Button(); this.btUp = new System.Windows.Forms.Button();
@@ -143,7 +142,7 @@
// //
// btConnect // btConnect
// //
this.btConnect.Location = new System.Drawing.Point(831, 64); this.btConnect.Location = new System.Drawing.Point(831, 90);
this.btConnect.Name = "btConnect"; this.btConnect.Name = "btConnect";
this.btConnect.Size = new System.Drawing.Size(165, 23); this.btConnect.Size = new System.Drawing.Size(165, 23);
this.btConnect.TabIndex = 5; this.btConnect.TabIndex = 5;
@@ -162,7 +161,7 @@
// //
// tbPassword // tbPassword
// //
this.tbPassword.Location = new System.Drawing.Point(910, 128); this.tbPassword.Location = new System.Drawing.Point(910, 64);
this.tbPassword.Name = "tbPassword"; this.tbPassword.Name = "tbPassword";
this.tbPassword.Size = new System.Drawing.Size(86, 20); this.tbPassword.Size = new System.Drawing.Size(86, 20);
this.tbPassword.TabIndex = 6; this.tbPassword.TabIndex = 6;
@@ -171,23 +170,12 @@
// lbPassword // lbPassword
// //
this.lbPassword.AutoSize = true; this.lbPassword.AutoSize = true;
this.lbPassword.Location = new System.Drawing.Point(828, 131); this.lbPassword.Location = new System.Drawing.Point(828, 67);
this.lbPassword.Name = "lbPassword"; this.lbPassword.Name = "lbPassword";
this.lbPassword.Size = new System.Drawing.Size(56, 13); this.lbPassword.Size = new System.Drawing.Size(56, 13);
this.lbPassword.TabIndex = 7; this.lbPassword.TabIndex = 7;
this.lbPassword.Text = "Password:"; this.lbPassword.Text = "Password:";
// //
// btLogin
//
this.btLogin.Enabled = false;
this.btLogin.Location = new System.Drawing.Point(831, 154);
this.btLogin.Name = "btLogin";
this.btLogin.Size = new System.Drawing.Size(165, 23);
this.btLogin.TabIndex = 8;
this.btLogin.Text = "Login";
this.btLogin.UseVisualStyleBackColor = true;
this.btLogin.Click += new System.EventHandler(this.btLogin_Click);
//
// btLeft // btLeft
// //
this.btLeft.Enabled = false; this.btLeft.Enabled = false;
@@ -298,7 +286,6 @@
this.Controls.Add(this.btUp); this.Controls.Add(this.btUp);
this.Controls.Add(this.btRight); this.Controls.Add(this.btRight);
this.Controls.Add(this.btLeft); this.Controls.Add(this.btLeft);
this.Controls.Add(this.btLogin);
this.Controls.Add(this.tbDataReceiving); this.Controls.Add(this.tbDataReceiving);
this.Controls.Add(this.lbPassword); this.Controls.Add(this.lbPassword);
this.Controls.Add(this.lbDataReceiving); this.Controls.Add(this.lbDataReceiving);
@@ -336,7 +323,6 @@
private System.Windows.Forms.Label lbServerIP; private System.Windows.Forms.Label lbServerIP;
private System.Windows.Forms.TextBox tbPassword; private System.Windows.Forms.TextBox tbPassword;
private System.Windows.Forms.Label lbPassword; private System.Windows.Forms.Label lbPassword;
private System.Windows.Forms.Button btLogin;
private System.Windows.Forms.Button btLeft; private System.Windows.Forms.Button btLeft;
private System.Windows.Forms.Button btRight; private System.Windows.Forms.Button btRight;
private System.Windows.Forms.Button btUp; private System.Windows.Forms.Button btUp;
+1 -4
View File
@@ -72,7 +72,7 @@ namespace ClientTest
} }
lbConnectionStatusText.Text = "Connecting..."; lbConnectionStatusText.Text = "Connecting...";
client.Connect(tbServerIP.Text, port, OnConnectionChanged, OnSend, OnReceived); client.Connect(tbServerIP.Text, port, tbPassword.Text, OnConnectionChanged, OnSend, OnReceived);
} }
private void Disconnect() private void Disconnect()
@@ -120,7 +120,6 @@ namespace ClientTest
{ {
lbConnectionStatusText.Text = "Connected"; lbConnectionStatusText.Text = "Connected";
btConnect.Text = "Disconnect"; btConnect.Text = "Disconnect";
btLogin.Enabled = true;
btUp.Enabled = true; btUp.Enabled = true;
btDown.Enabled = true; btDown.Enabled = true;
btLeft.Enabled = true; btLeft.Enabled = true;
@@ -136,8 +135,6 @@ namespace ClientTest
client.Disconnect(); client.Disconnect();
lbConnectionStatusText.Text = "Disconnected"; lbConnectionStatusText.Text = "Disconnected";
btConnect.Text = "Connect"; btConnect.Text = "Connect";
btLogin.Text = "Login";
btLogin.Enabled = false;
loggedIn = false; loggedIn = false;
btUp.Enabled = false; btUp.Enabled = false;
btDown.Enabled = false; btDown.Enabled = false;
Binary file not shown.
+5 -25
View File
@@ -44,7 +44,11 @@ namespace Vocaluxe.Base.Server
public static void Init() public static void Init()
{ {
_Clients = new Dictionary<int, CClientHandler>(); _Clients = new Dictionary<int, CClientHandler>();
_Server = new CServer(RequestHandler, CConfig.ServerPort, CConfig.ServerEncryption == EOffOn.TR_CONFIG_ON); if (CConfig.ServerEncryption == EOffOn.TR_CONFIG_ON)
_Server = new CServer(RequestHandler, CConfig.ServerPort, CConfig.ServerPassword);
else
_Server = new CServer(RequestHandler, CConfig.ServerPort, String.Empty);
_Discover = new CDiscover(CConfig.ServerPort, CCommands.BroadcastKeyword); _Discover = new CDiscover(CConfig.ServerPort, CCommands.BroadcastKeyword);
Controller.Init(); Controller.Init();
} }
@@ -88,30 +92,6 @@ namespace Vocaluxe.Base.Server
} }
int command = BitConverter.ToInt32(message, 0); int command = BitConverter.ToInt32(message, 0);
switch (command)
{
case CCommands.CommandLogin:
SLoginData data;
if (!CCommands.DecodeCommandLogin(message, out data))
answer = CCommands.CreateCommandWithoutParams(CCommands.ResponseLoginFailed);
else
{
byte[] serverPw = CCommands.SHA256.ComputeHash(Encoding.UTF8.GetBytes(CConfig.ServerPassword));
if (!serverPw.SequenceEqual(data.SHA256))
answer = CCommands.CreateCommandWithoutParams(CCommands.ResponseLoginWrongPassword);
else
{
answer = CCommands.CreateCommandWithoutParams(CCommands.ResponseLoginOK);
_Clients[connectionID].LoggedIn = true;
}
}
break;
}
if (!loggedIn)
return answer;
switch (command) switch (command)
{ {