Compare commits

45 Commits

Author SHA1 Message Date
kennyboy55 b4eef12eea Bugfix. Encode saved passwords 2015-10-21 09:20:22 +02:00
kennyboy55 7aeb20288e Don't send doctor as user 2015-10-20 23:40:06 +02:00
kennyboy55 85bcb0a2d4 Moved local ip to library 2015-10-20 22:49:59 +02:00
kennyboy55 d58e081bed Reduced threshold on writing metingen 2015-10-20 22:43:19 +02:00
kennyboy55 62bb9bec96 Added broadcast 2015-10-20 19:40:55 +02:00
kennyboy55 ad74945882 Fixed duplicate old sessions 2015-10-20 15:09:51 +02:00
Aareschluchtje 7bfa7def9a Merge remote-tracking branch 'origin/develop' into develop 2015-10-20 13:46:51 +02:00
Aareschluchtje 8ce439b2e4 Changed things 2015-10-20 13:46:46 +02:00
kennyboy55 c69bfda291 Added chat to old sessions 2015-10-20 12:58:37 +02:00
Aareschluchtje 558d569e05 Merge remote-tracking branch 'origin/develop' into develop
Conflicts:
	ErgometerServer/DoctorThread.cs
2015-10-20 12:05:09 +02:00
Aareschluchtje 801c0fd25f Changed old sessions 2015-10-20 12:03:12 +02:00
kennyboy55 50c2ceeb56 Bufixes 2015-10-20 11:18:44 +02:00
kennyboy55 d5bb2d555d Removed unused code. Fixed reading old metingen from file. 2015-10-20 00:27:57 +02:00
kennyboy55 18dc45d604 Better connection handling 2015-10-19 22:25:57 +02:00
kennyboy55 cd10139853 Moved thread to background 2015-10-19 18:52:45 +02:00
kennyboy55 891a3e0171 Removed test line 2015-10-19 17:31:53 +02:00
kennyboy55 6dd602c5b3 Bugfixes 2015-10-17 21:48:20 +02:00
Aareschluchtje 61e6e4ed93 Added temporary test for client 2015-10-16 13:16:15 +02:00
kennyboy55 df946b93de Bugfixes 2015-10-16 10:43:25 +02:00
kennyboy55 acf62eaaed Send length before data 2015-10-13 22:04:49 +02:00
Aareschluchtje abe3439623 Added some more stuff. 2015-10-11 15:22:43 +02:00
Aareschluchtje 81338c0477 Updated the switch case to include the new requests, 2015-10-10 22:39:58 +02:00
kennyboy55 61b837dd8a More stuff to do 2015-10-09 20:50:42 +02:00
Aareschluchtje d4caece905 Updated todo list 2015-10-09 12:18:52 +02:00
kennyboy55 5950fe3ac4 Merge remote-tracking branch 'origin/develop' into develop 2015-10-09 11:18:35 +02:00
kennyboy55 f8394b6bb1 Todo List 2015-10-09 11:18:17 +02:00
Aareschluchtje 7b5f4d811f Added add user (for doctor) 2015-10-09 11:00:27 +02:00
kennyboy55 5e0a0b25eb Added doctor stuff and user 2015-10-09 10:46:42 +02:00
kennyboy55 1744fdb74f Added login, bugfixes 2015-10-08 22:41:51 +02:00
kennyboy55 c6735fadc3 Added new functionality 2015-10-08 18:29:24 +02:00
Aareschluchtje 33697cfc3e totally changed communication between client and doctor. Needs to be tested. Also protocol needs to be changed to fix missing features. 2015-10-05 16:37:30 +02:00
Aareschluchtje c8f32ced43 More bullshit added. 2015-10-05 12:59:05 +02:00
Aareschluchtje 75d3bf1ec0 Cleaned up ServerConsole 2015-10-05 10:30:20 +02:00
Aareschluchtje eb5da5e514 Added saving files. 2015-10-04 14:48:38 +02:00
kennyboy55 1c404b0b0c Bugfix 2015-10-02 13:38:29 +02:00
kennyboy55 588555a8fd Updated properties 2015-10-02 12:51:50 +02:00
kennyboy55 7ebe13c398 Changed to library 2015-10-02 12:19:40 +02:00
Aareschluchtje a50bc20792 Made some bugfixes 2015-09-28 10:06:15 +02:00
Aareschluchtje 5aeca86e39 Changed back to localhost 2015-09-25 13:57:10 +02:00
Aareschluchtje 709956a59a Updated server to new library. 2015-09-25 12:53:20 +02:00
Aareschluchtje 2f7dae0016 Added static Ip 2015-09-25 09:37:41 +02:00
Aareschluchtje 721ee4378b Made some important changes in the server. 2015-09-23 21:29:37 +02:00
Aareschluchtje b2de4aff69 Server is now able to read data and confirm data it received. 2015-09-23 20:43:26 +02:00
Aareschluchtje b90dd0bfe1 Created a server (no real functionality yet). 2015-09-23 18:25:38 +02:00
kennyboy55 58baaebe08 First commit 2015-09-21 10:32:23 +02:00
9 changed files with 769 additions and 0 deletions
+22
View File
@@ -0,0 +1,22 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.23107.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ErgometerServer", "ErgometerServer\ErgometerServer.csproj", "{398293F9-9DF4-4F7A-AC85-6CF488B08B29}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{398293F9-9DF4-4F7A-AC85-6CF488B08B29}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{398293F9-9DF4-4F7A-AC85-6CF488B08B29}.Debug|Any CPU.Build.0 = Debug|Any CPU
{398293F9-9DF4-4F7A-AC85-6CF488B08B29}.Release|Any CPU.ActiveCfg = Release|Any CPU
{398293F9-9DF4-4F7A-AC85-6CF488B08B29}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
+137
View File
@@ -0,0 +1,137 @@
using ErgometerLibrary;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ErgometerServer
{
class ClientThread
{
TcpClient client;
Server server;
public string name;
public int session { get; }
bool running;
bool loggedin;
List<Meting> metingen;
List<ChatMessage> chat;
public ClientThread(TcpClient client, Server server)
{
this.client = client;
this.server = server;
this.name = "Unknown";
this.session = 0;
this.running = false;
this.loggedin = false;
metingen = new List<Meting>();
chat = new List<ChatMessage>();
session = FileHandler.GenerateSession();
Console.WriteLine("Generated new session: " + session);
}
public void run()
{
running = true;
NetHelper.SendNetCommand(client, new NetCommand(session));
while (running)
{
NetCommand input = NetHelper.ReadNetCommand(client);
switch(input.Type)
{
case NetCommand.CommandType.SESSION:
break;
case NetCommand.CommandType.LOGIN:
if(! server.CheckPassword(input.DisplayName, input.Password))
{
NetHelper.SendNetCommand(client, new NetCommand(NetCommand.ResponseType.LOGINWRONG, session));
loggedin = false;
}
else
{
NetHelper.SendNetCommand(client, new NetCommand(NetCommand.ResponseType.LOGINOK, session));
loggedin = true;
if (input.IsDoctor)
{
server.ChangeClientToDoctor(client, this);
Console.WriteLine("Doctor connected");
running = false;
}
else
{
name = input.DisplayName;
loggedin = true;
FileHandler.CreateSession(session, name);
}
}
break;
case NetCommand.CommandType.DATA:
if (loggedin)
{
metingen.Add(input.Meting);
server.SendToDoctor(input);
}
else
NetHelper.SendNetCommand(client, new NetCommand(NetCommand.ResponseType.NOTLOGGEDIN, session));
break;
case NetCommand.CommandType.CHAT:
if (loggedin)
{
chat.Add(new ChatMessage(name, input.ChatMessage, false));
server.SendToDoctor(input);
}
else
NetHelper.SendNetCommand(client, new NetCommand(NetCommand.ResponseType.NOTLOGGEDIN, session));
break;
case NetCommand.CommandType.LOGOUT:
loggedin = false;
running = false;
Console.WriteLine(name + " logged out");
FileHandler.WriteMetingen(session, metingen);
FileHandler.WriteChat(session, chat);
client.Close();
break;
case NetCommand.CommandType.ERROR:
Console.WriteLine("An error occured, assuming client disconnected");
loggedin = false;
running = false;
Console.WriteLine(name + " logged out due to an error");
FileHandler.WriteMetingen(session, metingen);
FileHandler.WriteChat(session, chat);
client.Close();
break;
default:
if(loggedin)
throw new FormatException("Unknown command");
break;
}
}
server.RemoveActiveSession(this);
}
public void SendToClient(NetCommand command)
{
NetHelper.SendNetCommand(client, command);
if (command.Type == NetCommand.CommandType.CHAT)
{
chat.Add(new ChatMessage("Doctor", command.ChatMessage, true));
}
}
}
}
+121
View File
@@ -0,0 +1,121 @@
using System;
using System.Collections;
using System.Net.Sockets;
using System.Runtime.Remoting.Lifetime;
using System.Threading;
using ErgometerLibrary;
using System.Collections.Generic;
namespace ErgometerServer
{
class DoctorThread
{
TcpClient client;
Server server;
bool running;
public DoctorThread(TcpClient client, Server server)
{
this.client = client;
this.server = server;
this.running = false;
}
public void run()
{
running = true;
while (running)
{
NetCommand input = NetHelper.ReadNetCommand(client);
switch (input.Type)
{
case NetCommand.CommandType.LOGOUT:
running = false;
client.Close();
Console.WriteLine("Doctor logged out");
break;
case NetCommand.CommandType.CHAT:
server.SendToClient(input);
break;
case NetCommand.CommandType.BROADCAST:
server.BroadcastToClients(input.ChatMessage);
break;
case NetCommand.CommandType.VALUESET:
server.SendToClient(input);
break;
case NetCommand.CommandType.USER:
server.AddUser(input.DisplayName, input.Password);
break;
case NetCommand.CommandType.REQUEST:
switch (input.Request)
{
case NetCommand.RequestType.USERS:
sendToDoctor(new NetCommand(NetCommand.LengthType.USERS, server.users.Count-1, input.Session));
foreach (KeyValuePair<string, string> user in server.users)
{
Thread.Sleep(10);
if(user.Key != "Doctor0tVfW")
sendToDoctor(new NetCommand(user.Key, user.Value, input.Session));
}
break;
case NetCommand.RequestType.CHAT:
List<ChatMessage> chat = FileHandler.ReadChat(input.Session);
foreach (ChatMessage msg in chat)
{
Thread.Sleep(10);
sendToDoctor(new NetCommand(msg.Message, msg.IsDoctor, input.Session));
}
break;
case NetCommand.RequestType.OLDDATA:
List<Meting> metingen = FileHandler.ReadMetingen(input.Session);
foreach (Meting meting in metingen)
{
Thread.Sleep(10);
sendToDoctor(new NetCommand(meting, input.Session));
}
break;
case NetCommand.RequestType.ALLSESSIONS:
List<Tuple<int, string, double>> sessions = FileHandler.GetAllSessions();
sendToDoctor(new NetCommand(NetCommand.LengthType.SESSIONS, sessions.Count, input.Session));
foreach(Tuple<int,string,double> session in sessions)
{
sendToDoctor(new NetCommand(session.Item2, session.Item3, session.Item1));
Thread.Sleep(10);
}
break;
case NetCommand.RequestType.SESSIONDATA:
List<Tuple<int, string>> currentsessionsdata = server.GetRunningSessionsData();
sendToDoctor(new NetCommand(NetCommand.LengthType.SESSIONDATA, currentsessionsdata.Count, input.Session));
foreach (Tuple<int, string> ses in currentsessionsdata)
{
sendToDoctor(new NetCommand(ses.Item2, Helper.Now, ses.Item1));
Thread.Sleep(10);
}
break;
default:
throw new FormatException("Unknown Command");
}
break;
case NetCommand.CommandType.ERROR:
Console.WriteLine("An error occured, assuming docter disconnected");
running = false;
Console.WriteLine("Doctor logged out due to an error");
client.Close();
break;
default:
throw new FormatException("Unknown Command");
}
}
}
public void sendToDoctor(NetCommand command)
{
NetHelper.SendNetCommand(client, command);
}
}
}
+72
View File
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{398293F9-9DF4-4F7A-AC85-6CF488B08B29}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ErgometerServer</RootNamespace>
<AssemblyName>ErgometerServer</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="ErgometerLibrary, Version=1.0.3.5, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\ErgometerLibrary\ErgometerLibrary\ErgometerLibrary\bin\Debug\ErgometerLibrary.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ClientThread.cs" />
<Compile Include="DoctorThread.cs" />
<Compile Include="FileHandler.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Server.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</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>
+204
View File
@@ -0,0 +1,204 @@
using ErgometerLibrary;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ErgometerServer
{
public class FileHandler
{
public static string DataFolder { get; } = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "Ergometer");
public static string UsersFile { get; } = Path.Combine(DataFolder, "users.ergo");
public static void CheckStorage()
{
if (!Directory.Exists(DataFolder))
{
Directory.CreateDirectory(DataFolder);
}
if (!File.Exists(UsersFile))
{
using (Stream stream = File.Open(UsersFile, FileMode.Create))
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(1);
writer.Write("Doctor0tVfW");
writer.Write(Helper.Base64Encode("password"));
}
}
}
//SESSION
public static int GenerateSession()
{
string[] existingSessions = Directory.GetDirectories(DataFolder);
Random rand = new Random();
int sessionID = rand.Next(0, int.MaxValue);
while (existingSessions.Contains(sessionID.ToString()))
{
sessionID = rand.Next(int.MinValue, int.MaxValue);
}
return sessionID;
}
public static void CreateSession(int session, string naam)
{
Directory.CreateDirectory(GetSessionFolder(session));
using (File.Create(Path.Combine(GetSessionFile(session)))) ;
using (File.Create(Path.Combine(GetSessionMetingen(session)))) ;
using (File.Create(Path.Combine(GetSessionChat(session)))) ;
File.WriteAllText(GetSessionFile(session), naam + Environment.NewLine + Helper.Now);
Console.WriteLine("Created session at " + Helper.MillisecondsToTime(Helper.Now));
}
public static void WriteMetingen(int session, List<Meting> metingen)
{
if (metingen.Count <= 20 && Directory.Exists(GetSessionFolder(session)))
{
Directory.Delete(GetSessionFolder(session), true);
}
else
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(metingen.ToArray());
File.WriteAllText(GetSessionMetingen(session), json);
Console.WriteLine("Writing metingen: " + GetSessionMetingen(session));
File.WriteAllText(GetSessionFile(session), File.ReadAllText(GetSessionFile(session)) + Environment.NewLine + Helper.Now);
}
}
public static List<Meting> ReadMetingen(int session)
{
string json = File.ReadAllText(GetSessionMetingen(session));
List<Meting> metingen = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Meting>>(json);
Console.WriteLine("Reading metingen: " + GetSessionMetingen(session));
return metingen;
}
public static List<Tuple<int, string, double>> GetAllSessions()
{
string[] directories = Directory.GetDirectories(DataFolder);
List<Tuple<int,string,double>> sessiondata = new List<Tuple<int, string, double>>();
for (int i = 0; i < directories.Length; i++)
{
string directoryname = Path.GetFileName(directories[i]);
string props = File.ReadAllText(GetSessionFile(int.Parse(directoryname)));
string[] stringSeparators = new string[] { "\r\n" };
string[] properties = props.Split(stringSeparators, StringSplitOptions.None);
int session = int.Parse(directoryname);
bool active = false;
foreach(ClientThread t in Server.clients)
{
if (t.session == session)
active = true;
}
string name = properties[0];
double date = double.Parse(properties[1]);
if (!active)
{
Tuple<int, string, double> tup = new Tuple<int, string, double>(session, name, date);
sessiondata.Add(tup);
}
}
return sessiondata;
}
public static void WriteChat(int session, List<ChatMessage> chat)
{
if (Directory.Exists(GetSessionFolder(session)))
{
/*
string write = "";
foreach (ChatMessage c in chat)
{
write += c.ToString() + "\n";
}
File.WriteAllText(GetSessionChat(session), write);
Console.WriteLine("Writing chat: " + GetSessionChat(session));
*/
string json = Newtonsoft.Json.JsonConvert.SerializeObject(chat.ToArray());
File.WriteAllText(GetSessionChat(session), json);
Console.WriteLine("Writing chat: " + GetSessionChat(session));
}
}
public static List<ChatMessage> ReadChat(int session)
{
string json = File.ReadAllText(GetSessionChat(session));
List<ChatMessage> chat = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ChatMessage>>(json);
return chat;
}
private static string GetSessionFolder(int session)
{
return Path.Combine(DataFolder, session.ToString());
}
private static string GetSessionFile(int session)
{
return Path.Combine(DataFolder, session.ToString(), "session.prop");
}
private static string GetSessionMetingen(int session)
{
return Path.Combine(DataFolder, session.ToString(), "metingen.ergo");
}
private static string GetSessionChat(int session)
{
return Path.Combine(DataFolder, session.ToString(), "chat.ergo");
}
//USER MANAGEMENT
public static Dictionary<string, string> LoadUsers()
{
Dictionary<string, string> users = new Dictionary<string, string>();
using (Stream stream = File.Open(UsersFile, FileMode.Open))
{
BinaryReader reader = new BinaryReader(stream);
int count = reader.ReadInt32();
for (int n = 0; n < count; n++)
{
var key = reader.ReadString();
var value = Helper.Base64Decode(reader.ReadString());
users.Add(key, value);
}
}
return users;
}
public static void SaveUsers(Dictionary<string, string> users)
{
using (Stream stream = File.Open(UsersFile, FileMode.Open))
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(users.Count);
foreach (var kvp in users)
{
writer.Write(kvp.Key);
writer.Write(Helper.Base64Encode(kvp.Value));
}
writer.Flush();
}
}
}
}
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ErgometerServer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ErgometerServer")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("398293f9-9df4-4f7a-ac85-6cf488b08b29")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+167
View File
@@ -0,0 +1,167 @@
using ErgometerLibrary;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace ErgometerServer
{
class Server
{
static void Main(string[] args)
{
new Server();
}
public static List<ClientThread> clients = new List<ClientThread>();
private DoctorThread doctor;
public Dictionary<string, string> users;
public Server()
{
AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);
FileHandler.CheckStorage();
users = FileHandler.LoadUsers();
TcpListener listener = new TcpListener(NetHelper.GetIP("127.0.0.1"), 8888);
//TcpListener listener = new TcpListener(NetHelper.GetIP(GetIp()), 8888);
listener.Start();
Console.WriteLine("Server started successfully...");
while (true)
{
Console.WriteLine("Waiting for connection with client...");
//AcceptTcpClient waits for a connection from the client
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Client connected");
//Start new client
ClientThread cl = new ClientThread(client, this);
clients.Add(cl);
//Run client on new thread
Thread thread = new Thread(new ThreadStart(cl.run));
thread.IsBackground = true;
thread.Start();
}
}
public void ChangeClientToDoctor(TcpClient client, ClientThread clth)
{
clients.Remove(clth);
doctor = new DoctorThread(client, this);
Thread thread = new Thread(new ThreadStart(doctor.run));
thread.IsBackground = true;
thread.Start();
}
public void SendToDoctor(NetCommand command)
{
if (doctor != null)
{
doctor.sendToDoctor(command);
}
}
public void BroadcastToClients(string message)
{
foreach (ClientThread clientThread in clients)
{
clientThread.SendToClient(new NetCommand(message, true, clientThread.session));
}
}
public void SendToClient(NetCommand command)
{
foreach (ClientThread clientThread in clients)
{
if (clientThread.session == command.Session)
{
clientThread.SendToClient(command);
}
}
}
public void AddUser(string name, string password)
{
users.Add(name, password);
FileHandler.SaveUsers(users);
}
public void AddUser(Dictionary<string, string> users)
{
foreach(KeyValuePair<string, string> user in users)
{
users.Add(user.Key, user.Value);
}
FileHandler.SaveUsers(users);
}
public bool CheckPassword(string name, string password)
{
string pass;
bool isOk = users.TryGetValue(name, out pass);
if (!isOk) return false;
return pass == password;
}
public List<int> GetRunningSessions()
{
List<int> sessions = new List<int>();
foreach (ClientThread thread in clients)
{
sessions.Add(thread.session);
}
return sessions;
}
public List<Tuple<int, string>> GetRunningSessionsData()
{
List<Tuple<int, string>> sessions = new List<Tuple<int, string>>();
foreach (ClientThread thread in clients)
{
sessions.Add(new Tuple<int, string>(thread.session, thread.name));
}
return sessions;
}
internal void RemoveActiveSession(ClientThread clientThread)
{
clients.Remove(clientThread);
}
private string GeneratePassword(int len = 8)
{
string pass = "";
char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();
Random rand = new Random();
for (int i=0; i<=len; i++)
{
pass += chars[rand.Next(0, chars.Length - 1)];
}
return pass;
}
private static void OnProcessExit(object sender, EventArgs e)
{
Console.WriteLine("Closing server");
}
}
}
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="7.0.1" targetFramework="net452" />
</packages>