TCPConnection.cs 10 KB

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