Posted By

Bajotumn on 03/15/10


Tagged


Versions (?)

Base receiver class for baisc tcp image transfer client/server


 / Published in: C#
 

Sets up a TCPServer to listen on the supplied thread then waits for packets and raises events or responds accordingly.

  1. using System;
  2. using System.Text;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Threading;
  6. using System.Drawing;
  7. using System.IO;
  8. using System.Collections.Generic;
  9.  
  10. namespace P2P_ScreenShare.Communications {
  11. /// <summary>
  12. /// A base class for receivers. Extends Communicator.
  13. /// </summary>
  14. public class Receiver : Communicator {
  15. private TcpListener pListener = null;
  16. /// <summary>
  17. /// If the server is listening this is true if not or if null it is false
  18. /// </summary>
  19. public bool Listening {
  20. get {
  21. if (pListener == null) {
  22. return false;
  23. }
  24. return this.pListener.Server.IsBound;
  25. }
  26. }
  27. public delegate void ImageReceivedHandler(IPEndPoint dSource, Image dImageReceived);
  28. public delegate void ImageRequestHandler(IPEndPoint dSource);
  29. public delegate void ClientEventHandler(IPEndPoint dSource);
  30.  
  31. public event ImageReceivedHandler ImageReceived = null;
  32. public event ImageRequestHandler ImageRequested = null;
  33. public event ClientEventHandler ClientConnected = null;
  34. public event ClientEventHandler ClientDisconnected = null;
  35.  
  36. private Thread ServerListenerThread = null;
  37. private List<Thread> ClientCommunicationThreads = new List<Thread>();
  38. public Receiver(string pIP, string pPort) {
  39. MyName = "Receiver";
  40. WriteColor = ConsoleColor.Cyan;
  41. SetEndPoint(pIP, pPort);
  42. this.pListener = new TcpListener(this.aEndPoint);
  43. SetSocket(pListener.Server);
  44. ServerListenerThread = new Thread(new ThreadStart(ServerListenHandler));
  45. }
  46. ~Receiver() {
  47. Stop();
  48. }
  49.  
  50. private void ServerListenHandler() {
  51. WriteLine("Server Listening on " + this.aEndPoint);
  52. while (true) {
  53. TcpClient cli = this.pListener.AcceptTcpClient();
  54. if (ClientConnected != null) {
  55. ClientConnected((IPEndPoint)cli.Client.RemoteEndPoint);
  56. }
  57. WriteLine("Client[" + cli.Client.RemoteEndPoint.ToString() + "] connected!");
  58. Thread cliComm = new Thread(new ParameterizedThreadStart(ClientCommunicationHandler));
  59. ClientCommunicationThreads.Add(cliComm);
  60. cliComm.Start(cli);
  61. }
  62. }
  63.  
  64. private void ClientCommunicationHandler(object o) {
  65. TcpClient tClient = (TcpClient)o;
  66. Socket sock = tClient.Client;
  67.  
  68. IPEndPoint cliEndPoint = (IPEndPoint)sock.RemoteEndPoint;
  69. while (tClient.Connected) {
  70. try {
  71. Packet packet = Receive(tClient.Client);
  72. if (packet != null) {
  73. if (!ParseReceivedData(packet, sock)) {
  74. WriteLine("The packet was not valid.");
  75. } else {
  76. tClient.Client.Send(new Packet(new byte[0x00], Packet.tPacketType.EMPTY).GetBytes());
  77. }
  78. } else {
  79. break;
  80. }
  81. } catch (SocketException sockEx) {
  82. WriteLine(sockEx.Message);
  83. break;
  84. }
  85. }
  86.  
  87. if (ClientDisconnected != null) {
  88. ClientDisconnected(cliEndPoint);
  89. }
  90. WriteLine("Closing connection to client [" + cliEndPoint + "]");
  91. tClient.Client.Close();
  92. tClient.Close();
  93. }
  94.  
  95. private bool ParseReceivedData(Packet packet, Socket sock) {
  96. string action = null;
  97. bool isValidPacket = false;
  98. switch (packet.PacketType) {
  99. case Packet.tPacketType.Ping:
  100. action = ("Responding");
  101. isValidPacket = true;
  102. sock.Send(packet.GetBytes());
  103. break;
  104. case Packet.tPacketType.ImageRequest:
  105.  
  106. isValidPacket = true;
  107. if (ImageRequested != null) {
  108. ImageRequested((IPEndPoint)sock.RemoteEndPoint);
  109. action = ("Raising event");
  110. } else {
  111. action = ("No event");
  112. }
  113. break;
  114. case Packet.tPacketType.Image:
  115. isValidPacket = true;
  116. Image lImage = GetImage(ByteSubArray(packet.Buffer, Packet.HEADER_SIZE));
  117. if (ImageReceived != null) {
  118. ImageReceived((IPEndPoint)sock.RemoteEndPoint, lImage);
  119. action = ("Raising event");
  120. } else {
  121. action = ("No event");
  122. }
  123. break;
  124. default:
  125. action = ("Unknown packet type!");
  126. break;
  127. }
  128. WriteLine("Received a(n) {0} packet...{1}", packet.PacketType, action);
  129. return isValidPacket;
  130. }
  131.  
  132. private Image GetImage(byte[] dataStream) {
  133. MemoryStream ms = new MemoryStream(dataStream);
  134. Image returnImage = Image.FromStream(ms);
  135. return returnImage;
  136. }
  137.  
  138. private byte[] ByteSubArray(byte[] data, int index) {
  139. byte[] ret = new byte[data.Length - index];
  140. int x = 0;
  141. for (int i = index; i < data.Length; i++) {
  142. ret[x++] = data[i];
  143. }
  144. return ret;
  145. }
  146.  
  147. public void Start() {
  148. if (Listening) {
  149. Stop();
  150. }
  151. this.pListener.Start();
  152. if (this.pListener.Server.IsBound) {
  153. ServerListenerThread.Start();
  154. } else {
  155. throw new Exception("The listener was not able to bind itself to the local port(" + this.aEndPoint.Port + ")!");
  156. }
  157. }
  158. public void Stop() {
  159. WriteLine("Stopped listening");
  160. Program.killThread(ServerListenerThread);
  161. ClientCommunicationThreads.ForEach(new Action<Thread>(Program.killThread));
  162. this.pListener.Server.Close();
  163. this.pListener.Stop();
  164.  
  165. }
  166. }
  167. }

Report this snippet  

You need to login to post a comment.