TCPConnection.cs 10 KB

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