TcpConnection.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. using FietsLibrary.JSONObjecten;
  2. using FietsLibrary;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Net.Security;
  8. using System.Net.Sockets;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Windows.Forms;
  12. using System.Security.Cryptography.X509Certificates;
  13. using System.Security.Authentication;
  14. using System.IO;
  15. namespace FietsClient
  16. {
  17. public class TcpConnection
  18. {
  19. public TcpClient client;
  20. public bool isConnectedFlag { private set; get; }
  21. private SslStream sslStream;
  22. public CurrentData currentData { private set; get; }
  23. public string userID { private set; get; }
  24. private Thread receiveThread;
  25. public delegate void ChatmassegeDelegate(string[] data);
  26. public event ChatmassegeDelegate IncomingChatmessageEvent;
  27. public TcpConnection()
  28. {
  29. client = new TcpClient();
  30. connect();
  31. }
  32. private void onIncomingChatMessage(string[] data)
  33. {
  34. ChatmassegeDelegate cMD = IncomingChatmessageEvent;
  35. if (cMD != null)
  36. {
  37. cMD(data);
  38. }
  39. }
  40. public bool isConnected()
  41. {
  42. return isConnectedFlag;
  43. }
  44. public void connect()
  45. {
  46. try
  47. {
  48. client.Connect("127.0.0.1", 1288);
  49. // create streams
  50. sslStream = new SslStream(client.GetStream(), false,
  51. new RemoteCertificateValidationCallback(CertificateValidationCallback),
  52. new LocalCertificateSelectionCallback(CertificateSelectionCallback));
  53. bool authenticationPassed = true;
  54. try
  55. {
  56. string serverName = System.Environment.MachineName;
  57. X509Certificate cert = GetServerCert();
  58. X509CertificateCollection certs = new X509CertificateCollection();
  59. certs.Add(cert);
  60. sslStream.AuthenticateAsClient(
  61. serverName,
  62. certs,
  63. SslProtocols.Default,
  64. false); // check cert revokation
  65. }
  66. catch (AuthenticationException)
  67. {
  68. authenticationPassed = false;
  69. }
  70. if (authenticationPassed)
  71. {
  72. receiveThread = new Thread(receive);
  73. receiveThread.Start();
  74. isConnectedFlag = true;
  75. }
  76. }
  77. catch (Exception ex)
  78. {
  79. Console.WriteLine(ex);
  80. Thread.Sleep(1000);
  81. isConnectedFlag = false;
  82. }
  83. }
  84. static X509Certificate CertificateSelectionCallback(object sender,
  85. string targetHost,
  86. X509CertificateCollection localCertificates,
  87. X509Certificate remoteCertificate,
  88. string[] acceptableIssuers)
  89. {
  90. return localCertificates[0];
  91. }
  92. private X509Certificate GetServerCert()
  93. {
  94. X509Certificate cert = new X509Certificate2(
  95. @"testcert.pfx",
  96. "jancoow");
  97. return cert;
  98. }
  99. private bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  100. {
  101. return true;
  102. }
  103. public void disconnect()
  104. {
  105. sslStream.Close();
  106. client.Close();
  107. receiveThread.Abort();
  108. isConnectedFlag = false;
  109. }
  110. public void receive()
  111. {
  112. while (client.Connected)
  113. {
  114. byte[] bytesFrom = new byte[(int)client.ReceiveBufferSize];
  115. try
  116. {
  117. sslStream.Read(bytesFrom, 0, client.ReceiveBufferSize);
  118. }
  119. catch (IOException e)
  120. {
  121. Console.WriteLine(e.StackTrace);
  122. break;
  123. }
  124. string response = Encoding.ASCII.GetString(bytesFrom);
  125. string[] response_parts = response.Split('|');
  126. if (response_parts.Length > 0)
  127. {
  128. switch (response_parts[0])
  129. {
  130. case "0": //login and display correct window after login
  131. if (response_parts.Length == 4)
  132. {
  133. if (response_parts[1] == "1" && response_parts[2] == "1")
  134. {
  135. currentData = new CurrentData(userID);
  136. currentData.isDoctor = true;
  137. SendGet(1);
  138. }
  139. else if (response_parts[2] == "0" && response_parts[1] == "1")
  140. {
  141. currentData = new CurrentData(userID);
  142. currentData.isDoctor = false;
  143. SendGet(1);
  144. }
  145. else
  146. new Login("Geen gebruiker gevonden");
  147. }
  148. break;
  149. case "1":
  150. response_parts[1] = response_parts[1].TrimEnd('\0');
  151. currentData.setSessionList(JsonConvert.DeserializeObject<List<Session>>(response_parts[1]));
  152. if (currentData.isDoctor == true)
  153. {
  154. Form activeForm = Form.ActiveForm;
  155. activeForm.Invoke((MethodInvoker)delegate ()
  156. {
  157. DoctorForm doctorForm = new DoctorForm(this);
  158. activeForm.Hide();
  159. doctorForm.Show();
  160. });
  161. }
  162. else
  163. {
  164. Form activeForm = Form.ActiveForm;
  165. if (activeForm != null)
  166. {
  167. activeForm.Invoke((MethodInvoker)delegate ()
  168. {
  169. PatientForm patientForm = new PatientForm(this);
  170. activeForm.Hide();
  171. patientForm.Show();
  172. });
  173. }
  174. }
  175. break;
  176. case "2":
  177. currentData.GetSessions().Last().AddMeasurement(JsonConvert.DeserializeObject<Measurement>(response_parts[1]));
  178. break;
  179. case "7":
  180. // sender receiver message
  181. onIncomingChatMessage(new string[] { response_parts[1], response_parts[2], response_parts[3].TrimEnd('\0') });
  182. break;
  183. case "8":
  184. if (response_parts[1].TrimEnd('\0') != "-1")
  185. {
  186. DoctorModel.doctorModel.onlinePatients = response_parts[1].TrimEnd('\0').Split('\t').ToList();
  187. }
  188. else if (response_parts[1].TrimEnd('\0') == "-1")
  189. {
  190. DoctorModel.doctorModel.onlinePatients = new List<String>();
  191. }
  192. break;
  193. case "9":
  194. JsonConvert.DeserializeObject<List<User>>(response_parts[1]);
  195. break;
  196. case "10":
  197. response_parts[1] = response_parts[1].TrimEnd('\0');
  198. if (!currentData.isDoctor)
  199. {
  200. if (response_parts[1] == "1")
  201. {
  202. StartNewSession();
  203. }
  204. else if (response_parts[1] == "0")
  205. {
  206. StopSessoin();
  207. }
  208. }
  209. break;
  210. }
  211. }
  212. }
  213. }
  214. public void StartNewSession()
  215. {
  216. Session session = new Session();
  217. currentData.sessions.Add(session);
  218. SendNewSession();
  219. PatientModel.patientModel.startAskingData();
  220. }
  221. public void StopSessoin()
  222. {
  223. PatientModel.patientModel.stopAskingData();
  224. }
  225. public void SendLogin(string username, string password)
  226. {
  227. // send command ( cmdID | username | password )
  228. this.userID = username;
  229. SendString("0|" + username + "|" + password + "|");
  230. }
  231. public void SendGet(int GetWhat)
  232. {
  233. // send command ( cmdID | username )
  234. SendString(GetWhat + "|" + userID + "|");
  235. }
  236. public void SendNewSession()
  237. {
  238. // send command ( cmdID | username )
  239. SendString("3|" + userID + "|" + FietsLibrary.JsonConverter.SerializeSession(currentData.GetSessions().Last()) + "|");
  240. }
  241. public void SendNewPatient(User user)
  242. {
  243. // send command ( cmdID | username )
  244. SendString("4|" + user.id + "|" + user.password + "|" + user.age + "|" + user.gender + "|" + user.weight + "|");
  245. }
  246. public void SendNewMeasurement()
  247. {
  248. // send command ( cmdID | username )
  249. SendString("5|" + userID + "|" + FietsLibrary.JsonConverter.SerializeLastMeasurement(currentData.GetSessions().Last().GetLastMeasurement()) + "|");
  250. }
  251. public void SendChatMessage(string[] data)
  252. {
  253. String receiverID = data[1];
  254. if (currentData != null)
  255. {
  256. String message = data[0];
  257. // send command ( cmdID | username sender | username receiverID | message )
  258. string protocol = "6|" + this.userID + "|" + receiverID + "|" + message;
  259. SendString(protocol);
  260. }
  261. }
  262. public void SendGetActivePatients()
  263. {
  264. SendString("8|" + userID + "|");
  265. }
  266. public void SendStartStopSession(bool startstop, string PatientUsername)
  267. {
  268. if (startstop)
  269. SendString("10|1|" + PatientUsername + "|");
  270. else
  271. SendString("10|0|" + PatientUsername + "|");
  272. }
  273. public void SendDistance(int distance)
  274. {
  275. SendString("20|" + userID + "|" + distance + "|");
  276. }
  277. public void SendTime(int Minutes, int seconds)
  278. {
  279. SendString("21|" + userID + "|" + Minutes + ":" + seconds + "|");
  280. }
  281. public void SendPower(int power)
  282. {
  283. SendString("22|" + userID + "|" + power + "|");
  284. }
  285. public void SendString(string s)
  286. {
  287. byte[] b = Encoding.ASCII.GetBytes(s);
  288. sslStream.Write(b, 0, b.Length);
  289. sslStream.Flush();
  290. }
  291. }
  292. }