Advertisement
Guest User

Untitled

a guest
Jan 17th, 2020
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.38 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. using System.Text.Json;
  7. using System.Threading;
  8.  
  9. namespace SocketClient {
  10. public class ClientInfo {
  11. public string studentnr { get; set; }
  12. public string classname { get; set; }
  13. public int clientid { get; set; }
  14. public string teamname { get; set; }
  15. public string ip { get; set; }
  16. public string secret { get; set; }
  17. public string status { get; set; }
  18. }
  19.  
  20. public class Message {
  21. public const string welcome = "WELCOME";
  22. public const string stopCommunication = "COMC-STOP";
  23. public const string statusEnd = "STAT-STOP";
  24. public const string secret = "SECRET";
  25. }
  26.  
  27. public class Client {
  28. public Socket clientSocket;
  29. private ClientInfo info;
  30. public IPEndPoint localEndPoint;
  31. public IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
  32. public readonly int portNumber = 11111;
  33. public readonly int minWaitingTime = 50, maxWaitingTime = 100;
  34. public int waitingTime = 0;
  35. string baseStdNumber = "0700";
  36.  
  37. public Client(bool finishing, int n) {
  38. waitingTime = new Random().Next(minWaitingTime, maxWaitingTime);
  39. info = new ClientInfo();
  40. info.classname = " INF2X ";
  41. info.studentnr = this.baseStdNumber + n.ToString();
  42. info.ip = "127.0.0.1";
  43. info.clientid = finishing ? -1 : 1;
  44. }
  45.  
  46. public string getClientInfo() {
  47. return JsonSerializer.Serialize<ClientInfo>(info);
  48. }
  49. public void prepareClient() {
  50. try {
  51. // Establish the remote endpoint for the socket.
  52. localEndPoint = new IPEndPoint(ipAddress, portNumber);
  53. // Creation TCP/IP Socket using
  54. clientSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  55. }
  56. catch (Exception e) {
  57. Console.Out.WriteLine("[Client] Preparation failed: {0}", e.Message);
  58. }
  59. }
  60. public string processMessage(string msg) {
  61. Console.WriteLine("[Client] from Server -> {0}", msg);
  62. string replyMsg = "";
  63.  
  64. try {
  65. switch (msg) {
  66. case Message.welcome:
  67. replyMsg = this.getClientInfo();
  68. break;
  69. default:
  70. ClientInfo c = JsonSerializer.Deserialize<ClientInfo>(msg.ToString());
  71. if (c.status == Message.statusEnd) {
  72. replyMsg = Message.stopCommunication;
  73. }
  74. break;
  75. }
  76. }
  77. catch (Exception e) {
  78. Console.Out.WriteLine("[Client] processMessage {0}", e.Message);
  79. }
  80. return replyMsg;
  81. }
  82. public void startCommunication() {
  83. Console.Out.WriteLine("[Client] **************");
  84. Thread.Sleep(waitingTime);
  85. // Data buffer
  86. byte[] messageReceived = new byte[1024];
  87. int numBytes = 0;
  88. String rcvdMsg = null;
  89. Boolean stop = false;
  90. string reply = "";
  91.  
  92. try {
  93. // Connect Socket to the remote endpoint
  94. clientSocket.Connect(localEndPoint);
  95. // print connected EndPoint information
  96. Console.WriteLine("[Client] connected to -> {0} ", clientSocket.RemoteEndPoint.ToString());
  97.  
  98. while (!stop) {
  99. // Receive the messagge using the method Receive().
  100. numBytes = clientSocket.Receive(messageReceived);
  101. rcvdMsg = Encoding.ASCII.GetString(messageReceived, 0, numBytes);
  102. reply = this.processMessage(rcvdMsg);
  103. this.sendReply(reply);
  104. if (reply.Equals(Message.stopCommunication)) {
  105. stop = true;
  106. }
  107. }
  108. }
  109. catch (Exception e) {
  110. Console.WriteLine(e.Message);
  111. }
  112. }
  113. public void sendReply(string msg) {
  114. // Create the message to send
  115. Console.Out.WriteLine("[Client] Message to be sent: {0}", msg);
  116. byte[] messageSent = Encoding.ASCII.GetBytes(msg);
  117. int byteSent = clientSocket.Send(messageSent);
  118. }
  119. public void endCommunication() {
  120. Console.Out.WriteLine("[Client] End of communication to -> {0} ", clientSocket.RemoteEndPoint.ToString());
  121. clientSocket.Shutdown(SocketShutdown.Both);
  122. clientSocket.Close();
  123. }
  124. }
  125.  
  126. public class ClientsSimulator {
  127. private int numberOfClients;
  128. private Client[] clients;
  129. public readonly int waitingTimeForStop = 2000;
  130. public List<Thread> threads = new List<Thread>();
  131.  
  132.  
  133. public ClientsSimulator(int n, int t) {
  134. numberOfClients = n;
  135. clients = new Client[numberOfClients];
  136. for (int i = 0; i < numberOfClients; i++) {
  137. clients[i] = new Client(false, i);
  138. }
  139. }
  140.  
  141. public void SequentialSimulation() {
  142. Console.Out.WriteLine("\n[ClientSimulator] Sequential simulator is going to start ...");
  143. for (int i = 0; i < numberOfClients; i++) {
  144. clients[i].prepareClient();
  145. clients[i].startCommunication();
  146. clients[i].endCommunication();
  147. }
  148.  
  149. Console.Out.WriteLine("\n[ClientSimulator] All clients finished with their communications ... ");
  150.  
  151. Thread.Sleep(waitingTimeForStop);
  152.  
  153. Client endClient = new Client(true, -1);
  154. endClient.prepareClient();
  155. endClient.startCommunication();
  156. endClient.endCommunication();
  157. }
  158.  
  159. public void ConcurrentSimulation() {
  160. Console.Out.WriteLine("[ClientSimulator] Concurrent simulator is going to start ...");
  161. // todo: In order to test the final solution, it is recommended to implement this method.
  162.  
  163. for (int i = 0; i < clients.Length; i++) {
  164. Client c = clients[i];
  165. threads.Add(new Thread(() => runClient(c)));
  166. }
  167.  
  168. foreach(Thread t in threads) {
  169. t.Start();
  170. }
  171.  
  172.  
  173. Console.Out.WriteLine("\n[ClientSimulator] All clients finished with their communications ... ");
  174. Thread.Sleep(waitingTimeForStop);
  175. Client endClient = new Client(true, -1);
  176. runClient(endClient);
  177.  
  178.  
  179. }
  180.  
  181. public void runClient(Client c) {
  182. c.prepareClient();
  183. c.startCommunication();
  184. c.endCommunication();
  185. }
  186. }
  187. public class Program {
  188. // Main Method
  189. public static void Main(string[] args) {
  190. Console.Clear();
  191. int wt = 1000, nc = 10;
  192. ClientsSimulator clientsSimulator = new ClientsSimulator(nc, wt);
  193. //clientsSimulator.SequentialSimulation();
  194. clientsSimulator.ConcurrentSimulation();
  195.  
  196. Console.WriteLine();
  197. Console.Read();
  198.  
  199. }
  200. }
  201. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement