TCPConnection.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 (true)
  111. {
  112. byte[] bytesFrom = new byte[(int)client.ReceiveBufferSize];
  113. sslStream.Read(bytesFrom, 0, client.ReceiveBufferSize);
  114. string response = Encoding.ASCII.GetString(bytesFrom);
  115. string[] response_parts = response.Split('|');
  116. if (response_parts.Length > 0)
  117. {
  118. switch (response_parts[0])
  119. {
  120. case "0": //login and display correct window after login
  121. if (response_parts.Length == 4)
  122. {
  123. SendGet(1);
  124. if (response_parts[1] == "1" && response_parts[2] == "1")
  125. {
  126. currentData = new CurrentData(userID);
  127. currentData.isDoctor = true;
  128. }
  129. else if (response_parts[2] == "0" && response_parts[1] == "1")
  130. {
  131. currentData = new CurrentData(userID);
  132. currentData.isDoctor = false;
  133. }
  134. else
  135. new Login("Geen gebruiker gevonden");
  136. }
  137. break;
  138. case "1":
  139. response_parts[1] = response_parts[1].TrimEnd('\0');
  140. currentData.setSessionList(JsonConvert.DeserializeObject<List<Session>>(response_parts[1]));
  141. if (currentData.isDoctor == true)
  142. {
  143. Form activeForm = Form.ActiveForm;
  144. activeForm.Invoke((MethodInvoker)delegate ()
  145. {
  146. DoctorForm doctorForm = new DoctorForm(this);
  147. activeForm.Hide();
  148. doctorForm.Show();
  149. });
  150. }
  151. else
  152. {
  153. Form activeForm = Form.ActiveForm;
  154. if (activeForm != null)
  155. {
  156. activeForm.Invoke((MethodInvoker)delegate ()
  157. {
  158. PatientForm patientForm = new PatientForm(this);
  159. activeForm.Hide();
  160. patientForm.Show();
  161. });
  162. }
  163. }
  164. break;
  165. case "2":
  166. currentData.GetSessions().Last().AddMeasurement(JsonConvert.DeserializeObject<Measurement>(response_parts[1]));
  167. break;
  168. case "7":
  169. // sender receiver message
  170. onIncomingChatMessage(new string[] { response_parts[1], response_parts[2], response_parts[3].TrimEnd('\0') });
  171. break;
  172. case "8":
  173. if (response_parts[1].TrimEnd('\0') != "-1")
  174. {
  175. DoctorModel.doctorModel.onlinePatients = response_parts[1].TrimEnd('\0').Split('\t').ToList();
  176. }
  177. else if (response_parts[1].TrimEnd('\0') == "-1")
  178. {
  179. DoctorModel.doctorModel.onlinePatients = new List<String>();
  180. }
  181. break;
  182. case "9":
  183. JsonConvert.DeserializeObject<List<User>>(response_parts[1]);
  184. break;
  185. }
  186. }
  187. }
  188. }
  189. public void SendLogin(string username, string password)
  190. {
  191. // send command ( cmdID | username | password )
  192. this.userID = username;
  193. SendString("0|" + username + "|" + password + "|");
  194. }
  195. public void SendGet(int GetWhat)
  196. {
  197. // send command ( cmdID | username )
  198. SendString(GetWhat + "|" + userID + "|");
  199. }
  200. public void SendNewSession()
  201. {
  202. // send command ( cmdID | username )
  203. SendString("3|" + userID + lib.JsonConverter.SerializeSession(currentData.GetSessions().Last()) + "|");
  204. }
  205. public void SendNewPatient(User user)
  206. {
  207. // send command ( cmdID | username )
  208. SendString("4|" + user.id + "|" + user.password + "|" + user.age + "|" + user.gender + "|" + user.weight + "|");
  209. }
  210. public void SendNewMeasurement()
  211. {
  212. // send command ( cmdID | username )
  213. SendString("5|" + userID + lib.JsonConverter.SerializeLastMeasurement(currentData.GetSessions().Last().GetLastMeasurement()) + "|");
  214. }
  215. public void SendChatMessage(string[] data)
  216. {
  217. String receiverID = data[1];
  218. if (currentData != null)
  219. {
  220. String message = data[0];
  221. // send command ( cmdID | username sender | username receiverID | message )
  222. string protocol = "6|" + this.userID + "|" + receiverID + "|" + message;
  223. SendString(protocol);
  224. }
  225. }
  226. public void SendGetActivePatients()
  227. {
  228. SendString("8|" + userID + "|");
  229. }
  230. public void SendDistance(int distance)
  231. {
  232. SendString("10|" + userID + "|" + distance + "|");
  233. }
  234. public void SendTime(int Minutes, int seconds)
  235. {
  236. SendString("11|" + userID + "|" + Minutes + ":" + seconds + "|");
  237. }
  238. public void SendPower(int power)
  239. {
  240. SendString("12|" + userID + "|" + power + "|");
  241. }
  242. public void SendString(string s)
  243. {
  244. byte[] b = Encoding.ASCII.GetBytes(s);
  245. sslStream.Write(b, 0, b.Length);
  246. sslStream.Flush();
  247. }
  248. }
  249. }