简体   繁体   中英

C# Socket receive data and send and receive again

I have a lot of GPS devices. One of my device (as client) send this message every minutes on TCP "[3G*4700201934*0009*LK,0,1,61]"

and my server have to read the message from GPS device and reply to device, I mean my server must send this message "[3G*4700201934*0009*LK]" for getting GPS positions. If I can't send this message, GPS device doesn't send the positions of GPS.

My code:

TcpListener listener = new TcpListener(IPAddress.Any, port);
listener.Start();

//Sonsuz döngü sayesinde AgAkimini sürekli okuyoruz
while (true)
{
    Socket client = listener.AcceptSocket();
    Console.WriteLine("Connection accepted.");

    var childSocketThread = new Thread(() =>
    {
        byte[] data = new byte[100];
        int size = client.Receive(data);
        string fromGPSMessage = string.Empty;
        for (int i = 0; i < size; i++)
            fromGPSMessage += Convert.ToChar(data[i]);
        Console.WriteLine("Recieved data: " + fromGPSMessage);
        //fromGPSMessage = [3G*4700201934*0009*LK,0,1,59]
        string serverMessageToGPS = fromGPSMessage.Substring(0, fromGPSMessage.IndexOf(",")) + "]";
        //serverMessageToGPS = [3G*4700201934*0009*LK]
        Encoding ascii = Encoding.ASCII;
        client.Send(ascii.GetBytes(serverMessageToGPS));

        data = new byte[100];
        size = client.Receive(data);
        string newMessagefromGPSMessage = string.Empty;
        for (int i = 0; i < size; i++)
            newMessagefromGPSMessage += Convert.ToChar(data[i]);
        Console.WriteLine("New Message Data: " + newMessagefromGPSMessage);

        client.Close();
    });
    childSocketThread.Start();
}

sometimes there is no new message data:

在此处输入图片说明

I can send message to device but I don't know how to get second message from GPS device.

It sounds like you need to read up on TcpClient : MSDN documentation

The example on that page shows you how to send data, and also how to read data returned to you.

You should create TCP OnReceive event. So when new data comes, OnReceive event executed and you can parse data.

In your code, you have written client.Receive(data), so it will receive data single time. To receive all data, you have to implement OnReceive event or you can put client.Receive(data) method in loop with threading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM