1

I have a GPS Tracker Device, I have run a TCP/IP Server Code which Successfully establishes connection with each device in a separate Thread and Device Keep sending its heart beat after one minute and server replies ON. When I send a command to get device location it gives me location and everything is working fine.

Now I want to get location from an android device using web service, Now I'm confuse how can I use running thread of a specific device from an Android App?

  • The Android webservice will be a two port application. One port is connected to the GPS Tracker Device using an IP address. The second port is a webpage application using HTTP (port 8080). In the application you will need a method of webpage app to get results from TCP class. – jdweng Dec 08 '17 at 12:56
  • Please explain, I think you have understand my problem. If I want to write Rest services then how will I use my device connection for that ? – Shehryar Khan Dec 08 '17 at 13:01
  • You will connect to service from client use a Webrequest (or any web method like WebClient) using the IP address of the android. The response will contain the GPS Tracker Location. The Rest will take results from TCP connection and reformat TCP bytes to a string and send in the response to client. – jdweng Dec 08 '17 at 13:05
  • But Device initiates the connection and then keeps sending its Heartbeat in a separate Thread. For getting its location I need to sent location I need to send location getting stream. If Device sending its Heartbeat on socket A then how will it give its location on any other socket ? – Shehryar Khan Dec 08 '17 at 13:29
  • I'm Sharing my code in Answer. – Shehryar Khan Dec 08 '17 at 13:29
  • Your Android App has an Application layer with two lower level ports (TCP to GPS and HTTP Listener to user). So the main in the app must start the two ports. Then wait for request command from user asking for GPS location, get location from GPS port, and finally send response to user on HTTP. – jdweng Dec 08 '17 at 13:37
  • also please guide me the way If I want to write REST APIs using C# which takes device IMEI and return device Location ? – Shehryar Khan Dec 08 '17 at 13:44

2 Answers2

0
class Server
{
    TcpListener server = null;
    public Server(string ip, int port)
    {
        IPAddress localAddr = IPAddress.Parse(ip);
        server = new TcpListener(localAddr, port);
        server.Start();
        StartListener();
    }

    public void StartListener()
    {
        try
        {
            while (true)
            {
                Console.WriteLine("Waiting for a connection... ");
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Connected!");

                Thread t = new Thread(new ParameterizedThreadStart(HandleDeivce));
                t.Start(client);
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
    }

    public void HandleDeivce(Object obj)
    {
        TcpClient client = (TcpClient)obj;
        NetworkStream stream = client.GetStream();

        string data = null;
        Byte[] bytes = new Byte[256];
        int i;

        while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
        {
            data = Encoding.ASCII.GetString(bytes, 0, i);
            Console.WriteLine("{1}: Received: {0}", data, Thread.CurrentThread.ManagedThreadId);

            if (data.StartsWith("##"))
            {
                data = "LOAD";
            }
            else
            {
                data = "ON";
            }

            byte[] msg = Encoding.ASCII.GetBytes(data);
            stream.Write(msg, 0, msg.Length);

            Console.WriteLine("{1}: Sent: {0}", data, Thread.CurrentThread.ManagedThreadId);
        }
        client.Close();
    }
}
0

Try making code look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;


namespace ConsoleApplication16
{
    class Program
    {
        const string IP = "123.456.789.000";
        const int PORT_NUMBER = 1234;
        static AutoResetEvent autoEvent = new AutoResetEvent(false);

        static void Main(string[] args)
        {
            GPSClient client = new GPSClient(IP, PORT_NUMBER);
            //start http client or equivalent here

            while (true)
            {
                autoEvent.Reset();

                autoEvent.WaitOne();

                //wait for message from user/client on service port

                string message = client.message;

                //send message back to user/client

            }
        }
    }
    public class WebServer
    {

    }
    public class GPSClient
    {
        const int BUFFER_SIZE = 256;
        TcpClient client = null;
        NetworkStream stream = null;
        Byte[] bytes = new Byte[BUFFER_SIZE];
        public string message { get; set; }



        public GPSClient(string ip, int port)
        {
            try
            {

                Console.WriteLine("Connecting to Device... ");

                client.Connect(ip, port);
                Console.WriteLine("Connected!");
                stream = client.GetStream();

                stream.BeginRead(bytes, 0, BUFFER_SIZE, new AsyncCallback(HandleDeivce), stream);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
        }

        public void HandleDeivce(IAsyncResult ar)
        {
            NetworkStream stream = ar.AsyncState as NetworkStream;

            string data = null;

            int i = stream.Read(bytes, 0, BUFFER_SIZE);

            data = Encoding.ASCII.GetString(bytes, 0, i);
            Console.WriteLine("Received: {0}", data);
            message = data;

            if (data.StartsWith("##"))
            {
               data = "LOAD";
            }
            else
            {
               data = "ON";
            }

            byte[] msg = Encoding.ASCII.GetBytes(data);
            stream.Write(msg, 0, msg.Length);

            Console.WriteLine("Sent: {0}", data);

            stream.BeginRead(bytes, 0, BUFFER_SIZE, new AsyncCallback(HandleDeivce), stream);
        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • Thanks but how can we write an API for reading a single parameter while this TCP listener is running. – Shehryar Khan Dec 11 '17 at 07:27
  • I wasn't sure what method you wanted for the user port. So added comments where the code belongs. If you give me a sample to the method you want to use for the user port I will update code. There are too many different methods you can use and wanted to provide the one you needed. – jdweng Dec 11 '17 at 08:04
  • I have posted my code in the answer above. please guide me the way. – Shehryar Khan Dec 11 '17 at 08:10
  • I only see one port for the GPS interface. Do not see any code for user interface. I need sample of the user interface which is another connection. – jdweng Dec 11 '17 at 08:29
  • Sir this is what I'm asking for. I have no idea that why I need another connection and how that connection will use this connection for reading a device parameter. I have no code for user interface. I just need a start for coding that part. – Shehryar Khan Dec 11 '17 at 08:54
  • I wan't sure if the service was in the PC on on the Android. I think you want the service running on Android. Look at following : https://stackoverflow.com/questions/8828639/get-gps-location-via-a-service-in-android. It creates a service on Android. You could need to add to the service a TCPListener so a PC can connect and get the GPS location. – jdweng Dec 11 '17 at 10:05
  • neither PC nor on android. I need to get location and other parameters of the GPS tracker device. – Shehryar Khan Dec 11 '17 at 13:49
  • I'm getting confused. Not sure how you want to use Android. Most Androids get GPS from Cell Tower and you do not need external device. I also do not know where your user interface is located. I initially thought the user interface was on Android. So the PC application needed two ports. One to talk to GPS Device and one to talk to Android. – jdweng Dec 11 '17 at 15:52
  • It's a GPS car Tracker and I want to develop an android app for this tracker so car owner can see his car on his android application – Shehryar Khan Dec 11 '17 at 16:02
  • https://www.google.com.pk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwj9wKzsqoLYAhUGtxoKHUGIBn0QFggkMAA&url=https%3A%2F%2Fsourceforge.net%2Fp%2Fopengts%2Fdiscussion%2F579835%2Fthread%2Fc0706b88%2F6fa0%2F4068%2Fattachment%2Fcoban%2520GPRS%2520PROTOCOL_COCO%2520HUO%2520%252020141212.pdf&usg=AOvVaw2f3bAQKAThhgLsWkCHGkNi – Shehryar Khan Dec 11 '17 at 16:05
  • this is device protocol document – Shehryar Khan Dec 11 '17 at 16:05
  • We are back to a two port application. One port TCP. Second Port HTTP. Do you have any code that you want to use for the HTTP port (webservice). Here is an example in c# (you can also use JSON) : https://www.codeproject.com/Articles/137979/Simple-HTTP-Server-in-C – jdweng Dec 11 '17 at 17:46