如何通过 TCP 连接获取 GPS 设备数据 GT06 CONCOX 协议 [英] How to Get GPS Devices data GT06 CONCOX Protocol over TCP connection

查看:28
本文介绍了如何通过 TCP 连接获取 GPS 设备数据 GT06 CONCOX 协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 GPS 设备接收数据:我有一个 TCP 服务器设置,它从各种 GPS 跟踪器 (GT06) 接收数据.每个 GPS 设备发起请求,服务器接受它,并开始接收 NMEA 数据.问题是当 GPS 连接到服务器时出现错误:远程主机强行关闭了现有连接"

问题是我不知道如何通过 GPRS/TCP 连接从 GPS 接收数据.有什么建议吗?

使用系统;使用 System.Collections.Generic;使用 System.Linq;使用 System.Net;使用 System.Net.Sockets;使用 System.Text;使用 System.Threading;使用 System.Threading.Tasks;命名空间 T1{课程计划{公共类 StateObject{公共常量 int DEFAULT_SIZE = 1024;//接收缓冲区大小公共字节[]缓冲区=新字节[DEFAULT_SIZE];//接收缓冲区公共 int 数据大小 = 0;//要接收的数据大小public bool dataSizeReceived = false;//接收到的数据大小?公共 StringBuilder sb = 新 StringBuilder();//接收到的数据字符串public int dataRecieved = 0;公共套接字 workSocket = null;//客户端套接字.公共日期时间时间戳;//数据时间戳公共常量 int BufferSize = 256;}//结束类StateObjectpublic static AutoResetEvent allDone = new AutoResetEvent(false);public static AutoResetEvent acceptDone = new AutoResetEvent(false);static void Main(string[] args){开始监听();}public static void StartListening(){//传入数据的数据缓冲区.字节[]字节=新字节[1024];//为套接字建立本地端点.//计算机的DNS名称//运行侦听器是host.contoso.com".IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());IPAddress ipAddress = ipHostInfo.AddressList[0];IPAddress local = IPAddress.Parse("103.118.16.129");IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8821);//创建一个 TCP/IP 套接字.套接字侦听器 = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);//将套接字绑定到本地端点并侦听传入连接.尝试{listener.Bind(localEndPoint);听者.听(100);而(真){//将事件设置为无信号状态.allDone.Reset();//启动一个异步套接字来监听连接.Console.WriteLine("正在等待连接...");listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);//等待连接建立后再继续.allDone.WaitOne();}}捕获(例外 e){Console.WriteLine(e.ToString());}//Console.WriteLine("\nPress ENTER to continue...");//Console.Read();}私有静态无效发送(套接字处理程序,字符串数据){//使用ASCII编码将字符串数据转换为字节数据.byte[] byteData = Encoding.ASCII.GetBytes(data);//开始向远程设备发送数据.handler.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), handler);}私有静态无效发送(套接字处理程序,字节[]数据){//使用ASCII编码将字符串数据转换为字节数据.//byte[] byteData = Encoding.ASCII.GetBytes(data);//开始向远程设备发送数据.handler.BeginSend(data, 0, data.Length, 0,new AsyncCallback(SendCallback), handler);}私有静态无效 SendCallback(IAsyncResult ar){尝试{//从状态对象中检索套接字.套接字处理程序 = (Socket)ar.AsyncState;//完成向远程设备发送数据.int bytesSent = handler.EndSend(ar);Console.WriteLine("向客户端发送了 {0} 个字节.", bytesSent);handler.Shutdown(SocketShutdown.Both);处理程序关闭();}捕获(例外 e){Console.WriteLine(e.ToString());}}公共静态无效 AcceptCallback(IAsyncResult ar){//通知主线程继续.allDone.Set();//获取处理客户端请求的套接字.套接字侦听器 = (Socket)ar.AsyncState;套接字处理程序 = listener.EndAccept(ar);//创建状态对象.StateObject state = new StateObject();state.workSocket = 处理程序;handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);}静态字节[]解包(字符串数据){//返回null表示错误列表<字节>bytes = new List();//检查开始和结束字节if ((data.Substring(0, 4) != "7878") && (data.Substring(data.Length - 4) != "0D0A")){返回空;}for (int index = 4; index < data.Length - 4; index += 2){bytes.Add(byte.Parse(data.Substring(index, 2), System.Globalization.NumberStyles.HexNumber));}//crc 测试byte[] packet = bytes.Take(bytes.Count - 2).ToArray();byte[] crc = bytes.Skip(bytes.Count - 2).ToArray();uint 计算的CRC = crc_bytes(packet);回包;}静态公共 UInt16 crc_bytes(byte[] 数据){ushort crc = 0xFFFF;for (int i = 0; i < data.Length; i++){crc ^= (ushort)(Reflect(data[i], 8) << 8);for (int j = 0; j <8; j++){如果 ((crc & 0x8000) > 0)crc = (ushort)((crc <<1) ^ 0x1021);别的CRC<<= 1;}}crc = 反射(crc,16);crc = (ushort)~crc;返回crc;}静态公共 ushort 反映(ushort 数据,整数大小){ushort 输出 = 0;for (int i = 0; i < size; i++){int lsb = 数据 &0x01;输出=(ushort)((输出<<1)| lsb);数据>>=1;}返回输出;}公共静态无效 ReadCallback(IAsyncResult ar){字符串内容 = String.Empty;//检索状态对象和处理程序套接字//来自异步状态对象.StateObject state = (StateObject)ar.AsyncState;套接字处理程序 = state.workSocket;//从客户端套接字读取数据.int bytesRead = handler.EndReceive(ar);如果(字节读取> 0){如果 (state.buffer[3] == 1){字符串输入 = BitConverter.ToString(state.buffer, 0, bytesRead).Replace("-", "");Console.WriteLine("收到 {0} 个字节给客户端.", input);//byte[] bytes = Unpack(input);//byte[] serialNumber = bytes.Skip(bytes.Length - 2).ToArray();//byte[] response = { 0x78, 0x78, 0x05, 0x01, 0x00, 0x00, 0x00, 0x0 };//serialNumber.CopyTo(response, 4);//UInt16 sendCRC = crc_bytes(response.Take(response.Length - 2).ToArray());//response[response.Length - 2] = (byte)((sendCRC >> 8) & 0xFF);//response[response.Length - 1] = (byte)((sendCRC) & 0xFF);//发送(处理程序,响应);//handler.Send(响应);}别的{//可能有更多的数据,所以存储到目前为止收到的数据.//state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));//检查文件结束标记.如果它不存在,请阅读//更多数据.//content = state.sb.ToString();Console.WriteLine("收到 {0} 个字节到客户端.", Encoding.ASCII.GetString(state.buffer, 0, bytesRead));//保存数据(内容);//不是所有的数据都收到了.获取更多.handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);//}}}}}

}

解决方案

@jdweng

先生,我尝试了您的建议,但同样的问题没有收到任何消息.

 使用系统;使用 System.Collections.Generic;使用 System.Diagnostics;使用 System.IO;使用 System.Linq;使用 System.Net;使用 System.Net.Sockets;使用 System.Text;使用 System.Threading;命名空间 T1{内部类程序{公共类 StateObject{公共常量 int DEFAULT_SIZE = 1024;//接收缓冲区大小公共字节[]缓冲区=新字节[DEFAULT_SIZE];//接收缓冲区公共 int 数据大小 = 0;//要接收的数据大小public bool dataSizeReceived = false;//接收到的数据大小?公共 StringBuilder sb = 新 StringBuilder();//接收到的数据字符串public int dataRecieved = 0;公共套接字 workSocket = null;//客户端套接字.公共日期时间时间戳;//数据时间戳公共常量 int BufferSize = 256;}//结束类StateObjectpublic static AutoResetEvent allDone = new AutoResetEvent(false);public static AutoResetEvent acceptDone = new AutoResetEvent(false);私有静态无效主(字符串 [] args){Write_log("StartListening");开始监听();}public static void StartListening(){//传入数据的数据缓冲区.字节[]字节=新字节[1024];//为套接字建立本地端点.IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 8821);//创建一个 TCP/IP 套接字.Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//将套接字绑定到本地端点并侦听传入连接.尝试{listener.Bind(localEndPoint);听者.听(100);//将事件设置为无信号状态.allDone.Reset();//启动一个异步套接字来监听连接.Console.WriteLine("正在等待连接...");Write_log("正在等待连接...");listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);//等待连接建立后再继续.allDone.WaitOne();Write_log("allDone");}捕获(例外 e){Console.WriteLine(e.ToString());}//Console.WriteLine("\nPress ENTER to continue...");//Console.Read();}私有静态无效发送(套接字处理程序,字符串数据){//使用ASCII编码将字符串数据转换为字节数据.byte[] byteData = Encoding.ASCII.GetBytes(data);//开始向远程设备发送数据.handler.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), handler);}私有静态无效发送(套接字处理程序,字节[]数据){//使用ASCII编码将字符串数据转换为字节数据.//byte[] byteData = Encoding.ASCII.GetBytes(data);//开始向远程设备发送数据.handler.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), handler);}私有静态无效 SendCallback(IAsyncResult ar){尝试{//从状态对象中检索套接字.套接字处理程序 = (Socket)ar.AsyncState;//完成向远程设备发送数据.int bytesSent = handler.EndSend(ar);Console.WriteLine("向客户端发送了 {0} 个字节.", bytesSent);handler.Shutdown(SocketShutdown.Both);处理程序关闭();}捕获(例外 e){Console.WriteLine(e.ToString());}}公共静态无效 AcceptCallback(IAsyncResult ar){//通知主线程继续.allDone.Set();//获取处理客户端请求的套接字.套接字侦听器 = (Socket)ar.AsyncState;套接字处理程序 = listener.EndAccept(ar);//创建状态对象.StateObject state = new StateObject();state.workSocket = 处理程序;handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);Write_log("ReadCallback...");}私有静态字节[] 解包(字符串数据){//返回null表示错误列表<字节>bytes = new List();//检查开始和结束字节if ((data.Substring(0, 4) != "7878") && (data.Substring(data.Length - 4) != "0D0A")){返回空;}for (int index = 4; index < data.Length - 4; index += 2){bytes.Add(byte.Parse(data.Substring(index, 2), System.Globalization.NumberStyles.HexNumber));}//crc 测试byte[] packet = bytes.Take(bytes.Count - 2).ToArray();byte[] crc = bytes.Skip(bytes.Count - 2).ToArray();uint 计算的CRC = crc_bytes(packet);回包;}静态公共 UInt16 crc_bytes(byte[] 数据){ushort crc = 0xFFFF;for (int i = 0; i < data.Length; i++){crc ^= (ushort)(Reflect(data[i], 8) << 8);for (int j = 0; j <8; j++){如果 ((crc & 0x8000) > 0)crc = (ushort)((crc <<1) ^ 0x1021);别的CRC<<= 1;}}crc = 反射(crc,16);crc = (ushort)~crc;返回crc;}静态公共 ushort 反映(ushort 数据,整数大小){ushort 输出 = 0;for (int i = 0; i < size; i++){int lsb = 数据 &0x01;输出 = (ushort)((输出 <<1) | lsb);数据>>=1;}返回输出;}公共静态无效 ReadCallback(IAsyncResult ar){字符串内容 = String.Empty;//检索状态对象和处理程序套接字//来自异步状态对象.StateObject state = (StateObject)ar.AsyncState;套接字处理程序 = state.workSocket;//从客户端套接字读取数据.int bytesRead = handler.EndReceive(ar);Write_log(bytesRead.ToString());如果(字节读取> 0){如果 (state.buffer[3] == 1){字符串输入 = BitConverter.ToString(state.buffer, 0, bytesRead).Replace("-", "");Console.WriteLine("收到 {0} 个字节给客户端.", input);//byte[] bytes = Unpack(input);//byte[] serialNumber = bytes.Skip(bytes.Length - 2).ToArray();//byte[] response = { 0x78, 0x78, 0x05, 0x01, 0x00, 0x00, 0x00, 0x0 };//serialNumber.CopyTo(response, 4);//UInt16 sendCRC = crc_bytes(response.Take(response.Length - 2).ToArray());//response[response.Length - 2] = (byte)((sendCRC >> 8) & 0xFF);//response[response.Length - 1] = (byte)((sendCRC) & 0xFF);//发送(处理程序,响应);//handler.Send(响应);}别的{//可能有更多的数据,所以存储到目前为止收到的数据.//state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));//检查文件结束标记.如果它不存在,请阅读//更多数据.//content = state.sb.ToString();Console.WriteLine("收到 {0} 个字节到客户端.", Encoding.ASCII.GetString(state.buffer, 0, bytesRead));//保存数据(内容);//不是所有的数据都收到了.获取更多.handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);//}}}}private static void Write_log(string logx){StringBuilder sb = new StringBuilder();string rootPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);sb.Append(logx);//每 20 秒刷新一次File.AppendAllText(rootPath + "//log.txt", sb.ToString());sb.清除();}}

}

Receiving data from GPS Device: I have a TCP server setup which is receiving data from various GPS Trackers (GT06). Each GPS devices initiates the request, server accepts it, and starts receiving NMEA data. Problem Is when GPS Connect to Server Error:"An existing connection was forcibly closed by the remote host"

The problem is that I don't know how to receive data from GPS over GPRS/TCP connection. Any suggestions?

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

namespace T1
{
        class Program
       {
    public class StateObject
    {
        public const int DEFAULT_SIZE = 1024;           //size of receive buffer

        public byte[] buffer = new byte[DEFAULT_SIZE];  //receive buffer
        public int dataSize = 0;                        //data size to be received
        public bool dataSizeReceived = false;           //received data size?
        public StringBuilder sb = new StringBuilder();  //received data String
        public int dataRecieved = 0;

        public Socket workSocket = null;                //client socket.
        public DateTime TimeStamp;                      //timestamp of data

        public const int BufferSize = 256;
    } //end class StateObject




    public static AutoResetEvent allDone = new AutoResetEvent(false);
    public static AutoResetEvent acceptDone = new AutoResetEvent(false);


    static void Main(string[] args)
    {



        StartListening();





   }


    public static void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        // The DNS name of the computer
        // running the listener is "host.contoso.com".
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPAddress local = IPAddress.Parse("103.118.16.129");
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8821);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and listen for incoming connections.
        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(100);

            while (true)
            {
                // Set the event to nonsignaled state.
                allDone.Reset();

                // Start an asynchronous socket to listen for connections.
                 Console.WriteLine("Waiting for a connection...");
                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);

                // Wait until a connection is made before continuing.
                allDone.WaitOne();
            }

        }
        catch (Exception e)
        {
             Console.WriteLine(e.ToString());
        }

        // Console.WriteLine("\nPress ENTER to continue...");
        // Console.Read();

    }

    private static void Send(Socket handler, String data)
    {
        // Convert the string data to byte data using ASCII encoding.
        byte[] byteData = Encoding.ASCII.GetBytes(data);

        // Begin sending the data to the remote device.
        handler.BeginSend(byteData, 0, byteData.Length, 0,
            new AsyncCallback(SendCallback), handler);
    }
    private static void Send(Socket handler, byte[] data)
    {
        // Convert the string data to byte data using ASCII encoding.
        // byte[] byteData = Encoding.ASCII.GetBytes(data);

        // Begin sending the data to the remote device.
        handler.BeginSend(data, 0, data.Length, 0,
            new AsyncCallback(SendCallback), handler);
    }

    private static void SendCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket handler = (Socket)ar.AsyncState;

            // Complete sending the data to the remote device.
            int bytesSent = handler.EndSend(ar);
             Console.WriteLine("Sent {0} bytes to client.", bytesSent);

            handler.Shutdown(SocketShutdown.Both);
            handler.Close();

        }
        catch (Exception e)
        {
             Console.WriteLine(e.ToString());
        }
    }


    public static void AcceptCallback(IAsyncResult ar)
    {
        // Signal the main thread to continue.
        allDone.Set();

        // Get the socket that handles the client request.
        Socket listener = (Socket)ar.AsyncState;
        Socket handler = listener.EndAccept(ar);

        // Create the state object.
        StateObject state = new StateObject();
        state.workSocket = handler;
        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
       new AsyncCallback(ReadCallback), state);
    }



    static byte[] Unpack(string data)
    {
        //return null indicates an error
        List<byte> bytes = new List<byte>();

        // check start and end bytes

        if ((data.Substring(0, 4) != "7878") && (data.Substring(data.Length - 4) != "0D0A"))
        {
            return null;
        }

        for (int index = 4; index < data.Length - 4; index += 2)
        {
            bytes.Add(byte.Parse(data.Substring(index, 2), System.Globalization.NumberStyles.HexNumber));
        }
        //crc test
        byte[] packet = bytes.Take(bytes.Count - 2).ToArray();
        byte[] crc = bytes.Skip(bytes.Count - 2).ToArray();

        uint CalculatedCRC = crc_bytes(packet);


        return packet;
    }


    static public UInt16 crc_bytes(byte[] data)
    {
        ushort crc = 0xFFFF;

        for (int i = 0; i < data.Length; i++)
        {
            crc ^= (ushort)(Reflect(data[i], 8) << 8);
            for (int j = 0; j < 8; j++)
            {
                if ((crc & 0x8000) > 0)
                    crc = (ushort)((crc << 1) ^ 0x1021);
                else
                    crc <<= 1;
            }
        }
        crc = Reflect(crc, 16);
        crc = (ushort)~crc;
        return crc;
    }


    static public ushort Reflect(ushort data, int size)
    {
        ushort output = 0;
        for (int i = 0; i < size; i++)
        {
            int lsb = data & 0x01;
            output = (ushort)((output << 1) | lsb);
            data >>= 1;
        }
        return output;
    }

    public static void ReadCallback(IAsyncResult ar)
    {
        String content = String.Empty;

        // Retrieve the state object and the handler socket
        // from the asynchronous state object.
        StateObject state = (StateObject)ar.AsyncState;
        Socket handler = state.workSocket;

        // Read data from the client socket. 
        int bytesRead = handler.EndReceive(ar);

        if (bytesRead > 0)
        {

            if (state.buffer[3] == 1)
            {

                string input = BitConverter.ToString(state.buffer, 0, bytesRead).Replace("-", "");


                Console.WriteLine("Recived {0} bytes to client.", input);

                //byte[] bytes = Unpack(input);

                //byte[] serialNumber = bytes.Skip(bytes.Length - 2).ToArray();

                //byte[] response = { 0x78, 0x78, 0x05, 0x01, 0x00, 0x00, 0x00, 0x0 };

                //serialNumber.CopyTo(response, 4);

                //UInt16 sendCRC = crc_bytes(response.Take(response.Length - 2).ToArray());

                //response[response.Length - 2] = (byte)((sendCRC >> 8) & 0xFF);
                //response[response.Length - 1] = (byte)((sendCRC) & 0xFF);

                //Send(handler, response);
                // handler.Send(response);
            }
            else
            {
                // There  might be more data, so store the data received so far.
                //state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                // Check for end-of-file tag. If it is not there, read 
                // more data.
                // content = state.sb.ToString();

                Console.WriteLine("Recived {0} bytes to client.", Encoding.ASCII.GetString(state.buffer, 0, bytesRead));


                //  SaveData(content);
                // Not all data received. Get more.
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
           new AsyncCallback(ReadCallback), state);
                // }
            }
        }
    }
}

}

解决方案

@jdweng

Sir I try your Suggestion But Same problem Not Receiving any Message.

 using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace T1
{
    internal class Program
    {
        public class StateObject
        {
            public const int DEFAULT_SIZE = 1024;           //size of receive buffer

        public byte[] buffer = new byte[DEFAULT_SIZE];  //receive buffer
        public int dataSize = 0;                        //data size to be received
        public bool dataSizeReceived = false;           //received data size?
        public StringBuilder sb = new StringBuilder();  //received data String
        public int dataRecieved = 0;

        public Socket workSocket = null;                //client socket.
        public DateTime TimeStamp;                      //timestamp of data

        public const int BufferSize = 256;
    } //end class StateObject

    public static AutoResetEvent allDone = new AutoResetEvent(false);
    public static AutoResetEvent acceptDone = new AutoResetEvent(false);

    private static void Main(string[] args)
    {
        Write_log("StartListening");
        StartListening();

    }

    public static void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 8821);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and listen for incoming connections.
        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(100);

            // Set the event to nonsignaled state.
            allDone.Reset();

            // Start an asynchronous socket to listen for connections.
            Console.WriteLine("Waiting for a connection...");
            Write_log("Waiting for a connection...");
            listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);

            // Wait until a connection is made before continuing.
            allDone.WaitOne();
            Write_log("allDone");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        // Console.WriteLine("\nPress ENTER to continue...");
        // Console.Read();
    }

    private static void Send(Socket handler, String data)
    {
        // Convert the string data to byte data using ASCII encoding.
        byte[] byteData = Encoding.ASCII.GetBytes(data);

        // Begin sending the data to the remote device.
        handler.BeginSend(byteData, 0, byteData.Length, 0,
            new AsyncCallback(SendCallback), handler);
    }

    private static void Send(Socket handler, byte[] data)
    {
        // Convert the string data to byte data using ASCII encoding.
        // byte[] byteData = Encoding.ASCII.GetBytes(data);

        // Begin sending the data to the remote device.
        handler.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), handler);
    }

    private static void SendCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket handler = (Socket)ar.AsyncState;

            // Complete sending the data to the remote device.
            int bytesSent = handler.EndSend(ar);
            Console.WriteLine("Sent {0} bytes to client.", bytesSent);

            handler.Shutdown(SocketShutdown.Both);
            handler.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    public static void AcceptCallback(IAsyncResult ar)
    {
        // Signal the main thread to continue.
        allDone.Set();

        // Get the socket that handles the client request.
        Socket listener = (Socket)ar.AsyncState;
        Socket handler = listener.EndAccept(ar);

        // Create the state object.
        StateObject state = new StateObject();
        state.workSocket = handler;
        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
       new AsyncCallback(ReadCallback), state);

        Write_log("ReadCallback...");
    }

    private static byte[] Unpack(string data)
    {
        //return null indicates an error
        List<byte> bytes = new List<byte>();

        // check start and end bytes

        if ((data.Substring(0, 4) != "7878") && (data.Substring(data.Length - 4) != "0D0A"))
        {
            return null;
        }

        for (int index = 4; index < data.Length - 4; index += 2)
        {
            bytes.Add(byte.Parse(data.Substring(index, 2), System.Globalization.NumberStyles.HexNumber));
        }
        //crc test
        byte[] packet = bytes.Take(bytes.Count - 2).ToArray();
        byte[] crc = bytes.Skip(bytes.Count - 2).ToArray();

        uint CalculatedCRC = crc_bytes(packet);

        return packet;
    }

    static public UInt16 crc_bytes(byte[] data)
    {
        ushort crc = 0xFFFF;

        for (int i = 0; i < data.Length; i++)
        {
            crc ^= (ushort)(Reflect(data[i], 8) << 8);
            for (int j = 0; j < 8; j++)
            {
                if ((crc & 0x8000) > 0)
                    crc = (ushort)((crc << 1) ^ 0x1021);
                else
                    crc <<= 1;
            }
        }
        crc = Reflect(crc, 16);
        crc = (ushort)~crc;
        return crc;
    }

    static public ushort Reflect(ushort data, int size)
    {
        ushort output = 0;
        for (int i = 0; i < size; i++)
        {
            int lsb = data & 0x01;
            output = (ushort)((output << 1) | lsb);
            data >>= 1;
        }
        return output;
    }

    public static void ReadCallback(IAsyncResult ar)
    {
        String content = String.Empty;

        // Retrieve the state object and the handler socket
        // from the asynchronous state object.
        StateObject state = (StateObject)ar.AsyncState;
        Socket handler = state.workSocket;

        // Read data from the client socket.
        int bytesRead = handler.EndReceive(ar);

        Write_log(bytesRead.ToString());

        if (bytesRead > 0)
        {
            if (state.buffer[3] == 1)
            {
                string input = BitConverter.ToString(state.buffer, 0, bytesRead).Replace("-", "");

                Console.WriteLine("Recived {0} bytes to client.", input);

                //byte[] bytes = Unpack(input);

                //byte[] serialNumber = bytes.Skip(bytes.Length - 2).ToArray();

                //byte[] response = { 0x78, 0x78, 0x05, 0x01, 0x00, 0x00, 0x00, 0x0 };

                //serialNumber.CopyTo(response, 4);

                //UInt16 sendCRC = crc_bytes(response.Take(response.Length - 2).ToArray());

                //response[response.Length - 2] = (byte)((sendCRC >> 8) & 0xFF);
                //response[response.Length - 1] = (byte)((sendCRC) & 0xFF);

                //Send(handler, response);
                // handler.Send(response);
            }
            else
            {
                // There  might be more data, so store the data received so far.
                //state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                // Check for end-of-file tag. If it is not there, read
                // more data.
                // content = state.sb.ToString();

                Console.WriteLine("Recived {0} bytes to client.", Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                //  SaveData(content);
                // Not all data received. Get more.
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                // }
            }
        }
    }

    private static void Write_log(string logx)
    {
        StringBuilder sb = new StringBuilder();

        string rootPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);

        sb.Append(logx);

        // flush every 20 seconds as you do it
        File.AppendAllText(rootPath + "//log.txt", sb.ToString());
        sb.Clear();
    }
}

}

这篇关于如何通过 TCP 连接获取 GPS 设备数据 GT06 CONCOX 协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆