目前,客户端发送的消息如下:
Public Function checkMD5(ByVal userID As Integer, ByVal gameID As Integer, ByVal file As String, ByVal fileFull As String) As String
Dim make As New CMakeMSG
Dim md5 As New CMD5
make.append("checkfileMD5")
make.append(userID)
make.append(containerID)
make.append(file)
make.append(md5.GenerateFileHash(fileFull))
Return SocketSendAndReceiveMSG(make.makestring)
End Function服务器可能会收到如下内容:
checkfileMD5-MSGDelimit0-12-MSGDelimit1-54-MSGDelimit2-filename.txt-MSGDelimit3-*md5hash*
然后它会读出:
Private _message As String
Public Function handleMessage() As String
Dim brokenMessage As New ArrayList
brokenMessage = breakDown() 'Split to ArrayList
If brokenMessage(0) = "checkfileMD5" Then
Try
If brokenMessage.Count > 5 Then
Return "0-structureMessedUp"
End If
Return CompareFileMD5(brokenMessage(1), brokenMessage(2), brokenMessage(3), brokenMessage(4))
Catch ex As Exception
Return "0-structureMessedUp"
End Try
End If
End Function因此,它所做的就是接收收到的消息,并使用-MSGDelimit作为分隔符将其拆分到一个数组中。因此,在本例中,CompareFileMD5()函数将接收12,54,filename.txt,*md5hash*。并且在此基础上,它可以向客户端返回MD5是否匹配。
当然,它可以工作,但它感觉很草率,服务器上的代码变得非常混乱。
下面是上面代码中不太相关的函数(怀疑这很重要,但你永远不会知道):
Private Function breakDown() As ArrayList
Try
Dim theArray As New ArrayList
Dim copymsg As String = _message
Dim counter As Integer = 0
Do Until Not copymsg.Contains("-MSGDelimit")
Dim found As String
found = copymsg.Substring(0, copymsg.IndexOf("-MSGDelimit" & counter & "-"))
theArray.Add(found)
copymsg = copymsg.Replace(found & "-MSGDelimit" & counter & "-", "")
counter += 1
Loop
theArray.Add(copymsg)
Return theArray
Catch ex As Exception
Module1.msg(ex.Message)
End Try
End Function
Private Function CompareFileMD5(ByVal userID As Integer, ByVal gameID As Integer, ByVal filename As String, ByVal source As String) As String
Try
Dim tryFindFile As String = Module1.filedatabase.findfile(userID, gameID, filename)
If Not tryFindFile = "notFound" Then
Dim fileFull As String = tryFindFile & "\" & filename
Dim md5 As New CMD5
If md5.GenerateFileHash(fileFull) = source Then
Return "Match"
Else
Return "NoMatch"
End If
Else
Return "notFound"
End If
Catch ex As Exception
Module1.msg("0")
Return "0"
End Try
End Function那么,对于如何更好地/更干净/更专业地处理它,有什么建议吗?
发布于 2012-02-23 00:05:50
根据应用程序的不同,您当前的解决方案可能完全没有问题。有几件事确实有一点突出:
假设所示的示例是许多类似协议中的一个,我倾向于采用不同的路线。一种可能是将请求捆绑为一个JSON对象。现有的包可用于创建和读取JSON。Json.NET就是一个例子。JSON具有定义良好的结构,易于阅读和验证,并且易于扩展。根据您发送的数据,它可能比当前格式更轻量级一些。而且(也许你感兴趣的部分),它可能看起来更“专业”。
我还会做几件额外的事情(个人观点):
https://stackoverflow.com/questions/9397412
复制相似问题