TCPConnection.cs 9.8 KB

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