TCPConnection.cs 9.7 KB

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