From the communication in the previous chapter, we found that if Tcp is used to send messages continuously, messages will be sent together, which causes some problems for programming, it may cause some problems for our information parsing. This article will provide a solution to the above problems ......
The problem usually occurs as follows. Suppose we send two consecutive two-day records ("I am liger_zql "):
Sending simulation example:
Test message sending and match protocol = (I =; I <; I ++ = MessageProtocol (, I +
1. (1) I am liger_zql (2) I am liger_zql
2. (1) I am liger_zql. I am (2) liger_zql.
3. (1) I am liger_zql and I am liger_zql
In the preceding three cases, both 2 and 3 are not the expected results. So how can we deal with this situation?
Solution: use custom protocols...
We can send the information in xml format and include the information in <protocol> content </protocol> to check whether the information is complete through regular expression matching. If the information is incomplete, we can cache this acceptance information to accept the next information and then match it again to obtain the corresponding result.
Convert the information object to an xml string in a certain format:
Content { ; ; } MessageInfo(.Content = String.Format(, Address { ; ; } Port { ; ; } RequestMode Mode { ; ; } FileObject FileObject { ; ; } .Mode =.FileObject = RequestFile( address, .Address =.Port =.Mode =.FileObject = RequestFile( address, port, RequestMode mode, filename, filelength, packetsize, .Address =.Port =.Mode =.FileObject = = MessageType MessageType { ; MessageInfo MessageInfo { ; RequestFile RequestFile { ; MessageProtocol(== == MessageProtocol( address, == = (MessageType == Encoding.UTF8.GetBytes(
Match the received information using regular expressions:
temp = List<MessageProtocol> HandlerString(<MessageProtocol> msgProList = List<MessageProtocol> (!= temp + pattern = match = Regex.Match(msg, pattern).Groups[= msg = (!=
Then, the defined protocol is converted into an information object, and the desired information is obtained through the object.
MessageProtocol HandlerObject(= == root.SelectSingleNode(= (root.Attributes[].Value ==== MessageInfo(msgnode.Attributes[== (RequestMode)Enum.Parse((RequestMode), msgnode.Attributes[= = msgnode.Attributes[= Convert.ToInt64(msgnode.Attributes[= Convert.ToInt32(msgnode.Attributes[= Convert.ToInt64(msgnode.Attributes[=
The final running result is as follows:
We have fixed the Tcp packet sticking problem. In the next chapter, we will solve the Udp packet loss personal solution!
Attached source code: SocketProQuests.zip