Read variables of a message that is sent by a serv

2019-03-06 10:42发布

I am working on Passenger information system PIS(Train).So trains send their location to my server PIS using socket on port 8080 .So i should get their locations and show them to passengers . The message that comes from the trains has a template that i should follow that. As you can see here :

enter image description here

So as you can see here we have 6 variables .every integer is 4 byte. The first variable is(4 byte) message source and etc.

In my server i have to detect these variable but i don't know how can i detect them from the message .

 static void Listeners()
        {

            Socket socketForClient = tcpListener.AcceptSocket();
            if (socketForClient.Connected)
            {
                Console.WriteLine("Client:" + socketForClient.RemoteEndPoint + " now connected to server.");
                NetworkStream networkStream = new NetworkStream(socketForClient);
                System.IO.StreamWriter streamWriter =
                new System.IO.StreamWriter(networkStream);
                System.IO.StreamReader streamReader =
                new System.IO.StreamReader(networkStream);

                while (true)
                {

                    TimeTableRepository objTimeTableRepository = new TimeTableRepository();
                    SensorRepository objSensorRepository = new SensorRepository();
                    ArrivalTimeRepository objArrivalTimeRepository=new ArrivalTimeRepository();
                    TrainRepository objTrainRepository = new TrainRepository();
                   // OnlineTrainRepository ObjOnlineTrainrepository = new OnlineTrainRepository();

                    //-----
                    string theString = streamReader.ReadLine();

                }
         }
}

Here is my listener to port 8080 and theString is the message that is send by trains.My problem is how can i detect this parameters (Message source,message destination and etc) from theString?I mean i need the value of them to store in database .

best regards

1条回答
迷人小祖宗
2楼-- · 2019-03-06 11:18

Looks like you don't need to detect anything and definitely should not be slapping this in a string to try and parse.

You already know you are getting a bunch of integers back. You even know what order they are in. Use a BinaryReader to get you your numbers and proceed from there. Once you load your reader up, it should be as simple as calling BinaryReader.ReadInt32() to read the message's numbers one after another.

I must also highly recommend you to look into using statements for your streams.

using (var reader = new BinaryReader(networkStream))
{
    var messageSource = reader.ReadInt32();
    var messageDestination = reader.ReadInt32();

    ... and so on ...
}
查看更多
登录 后发表回答