TCPConnection.cs 10 KB

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