00001 using System;
00002 using System.Net;
00003 using System.Net.Sockets;
00004 using System.Threading;
00005
00006
00007 namespace GPRSWeb.SmartDeviceClient.SmartProtocolStack
00008 {
00012 public class SegmentReceiver {
00013 Thread processingThread;
00014 StackInterface thisStack;
00015 UdpClient udpListener;
00016
00021 public SegmentReceiver(StackInterface thisStack) {
00022 this.thisStack = thisStack;
00023 }
00024
00025 public void Start() {
00026 thisStack.msgLog.LogStartBegin("Segment Receiver");
00027 processingThread = new Thread(new ThreadStart(Listen));
00028 processingThread.Start();
00029 thisStack.msgLog.LogStartComplete("Segment Receiver");
00030 }
00031
00033 private void Listen() {
00034 IPEndPoint currentEndPoint;
00035 Segment receivedSegment;
00036 int localPortNumber = -1;
00037 if (thisStack.settings.MyDeviceID == thisStack.Settings.SERVER_DEVICE_ID) {
00038 localPortNumber = thisStack.Settings.ServerReceivePortNumber;
00039 } else {
00040 localPortNumber = thisStack.Settings.ClientReceivePortNumber;
00041 }
00042
00043 udpListener = new UdpClient(new IPEndPoint(IPAddress.Any, localPortNumber));
00044 try {
00045 while(true) {
00046 try {
00047
00048 currentEndPoint = new IPEndPoint(IPAddress.Any, localPortNumber);
00049 receivedSegment = new Segment(udpListener.Receive(ref currentEndPoint));
00050 receivedSegment.Headers.TimeReceived = DateTime.Now.ToUniversalTime();
00051 Console.WriteLine("Got segment #{0}", receivedSegment.Headers.SequenceNumber);
00052 thisStack.GetRemoteHostByID(receivedSegment.Headers.SourceDeviceID).AcceptIncomingSegment(receivedSegment);
00053 } catch (Exception ex) {
00054 thisStack.msgLog.LogError("Error in Protocol Stack\n\rUnable to correctly receive segment.\n\rSkipping over and continuting. Details:\n\r(" + ex + ")");
00055 }
00056 }
00057 } finally {
00058 if (udpListener != null) { udpListener.Close(); }
00059 }
00060 }
00061 }
00062
00063
00064 }