TCPConnection.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. currentData.setSessionList(JsonConvert.DeserializeObject<List<Session>>(response_parts[1]));
  140. if (currentData.isDoctor == true)
  141. {
  142. Form activeForm = Form.ActiveForm;
  143. activeForm.Invoke((MethodInvoker)delegate ()
  144. {
  145. DoctorForm doctorForm = new DoctorForm(this);
  146. activeForm.Hide();
  147. doctorForm.Show();
  148. });
  149. }
  150. else
  151. {
  152. Form activeForm = Form.ActiveForm;
  153. if (activeForm != null)
  154. {
  155. activeForm.Invoke((MethodInvoker)delegate ()
  156. {
  157. PatientForm patientForm = new PatientForm(this);
  158. activeForm.Hide();
  159. patientForm.Show();
  160. });
  161. }
  162. }
  163. break;
  164. case "2":
  165. currentData.GetSessions().Last().AddMeasurement(JsonConvert.DeserializeObject<Measurement>(response_parts[1]));
  166. break;
  167. case "7":
  168. // sender receiver message
  169. onIncomingChatMessage(new string[] { response_parts[1], response_parts[2], response_parts[3].TrimEnd('\0') });
  170. break;
  171. case "8":
  172. if (response_parts[1].TrimEnd('\0') != "-1")
  173. {
  174. DoctorModel.doctorModel.onlinePatients = response_parts[1].TrimEnd('\0').Split('\t').ToList();
  175. }
  176. else if (response_parts[1].TrimEnd('\0') == "-1")
  177. {
  178. DoctorModel.doctorModel.onlinePatients = new List<String>();
  179. }
  180. break;
  181. }
  182. }
  183. }
  184. }
  185. public void SendLogin(string username, string password)
  186. {
  187. // send command ( cmdID | username | password )
  188. this.userID = username;
  189. SendString("0|" + username + "|" + password + "|");
  190. }
  191. public void SendGet(int GetWhat)
  192. {
  193. // send command ( cmdID | username )
  194. SendString(GetWhat + "|" + userID + "|");
  195. }
  196. public void SendNewSession()
  197. {
  198. // send command ( cmdID | username )
  199. SendString("3|" + userID + lib.JsonConverter.SerializeSession(currentData.GetSessions().Last()) + "|");
  200. }
  201. public void SendNewMeasurement()
  202. {
  203. // send command ( cmdID | username )
  204. SendString("5|" + userID + lib.JsonConverter.SerializeLastMeasurement(currentData.GetSessions().Last().GetLastMeasurement()) + "|");
  205. }
  206. public void SendChatMessage(string[] data)
  207. {
  208. String receiverID = data[1];
  209. if (currentData != null)
  210. {
  211. String message = data[0];
  212. // send command ( cmdID | username sender | username receiverID | message )
  213. string protocol = "6|" + this.userID + "|" + receiverID + "|" + message;
  214. SendString(protocol);
  215. }
  216. }
  217. public void SendGetActivePatients()
  218. {
  219. SendString("8|" + userID + "|");
  220. }
  221. public void SendDistance(int distance)
  222. {
  223. SendString("10|" + userID + "|" + distance + "|");
  224. }
  225. public void SendTime(int Minutes, int seconds)
  226. {
  227. SendString("11|" + userID + "|" + Minutes + ":" + seconds + "|");
  228. }
  229. public void SendPower(int power)
  230. {
  231. SendString("12|" + userID + "|" + power + "|");
  232. }
  233. public void SendString(string s)
  234. {
  235. byte[] b = Encoding.ASCII.GetBytes(s);
  236. sslStream.Write(b, 0, b.Length);
  237. sslStream.Flush();
  238. }
  239. }
  240. }