我制作了一个 TCP/IP 服务器/客户端,它是异步的,但它连接了消息。我如何正确地在开始时添加一个标题,然后在最后使用一个字符串生成器来取消连接完整的消息。
服务器读取消息:
Private Sub ReadCallback(ByVal result As IAsyncResult)
Try
allDone.Set()
Dim success As Boolean = result.AsyncWaitHandle.WaitOne(500, True)
If success Then
Dim client As ServerClient = TryCast(result.AsyncState, ServerClient)
If client Is Nothing Then
Return
End If
Dim networkStream As NetworkStream = client.NetworkStream
Dim read As Integer = networkStream.EndRead(result)
If read = 0 Then
SyncLock Me.Clients
Me.Clients.Remove(client.ClientID)
Return
End SyncLock
End If
If client.NetworkStream.CanRead Then
dataString.Append(Me.Encoding.GetString(client.buffer, 0, read))
networkStream.BeginRead(client.buffer, 0, client.buffer.Length, AddressOf ReadCallback, client)
allDone.WaitOne(500, True)
End If
End If
Catch ex As IO.IOException
Dim client As ServerClient = TryCast(result.AsyncState, ServerClient)
SyncLock Me.Clients
Me.Clients.Remove(client.ClientID)
Return
End SyncLock
Catch ex As Exception
If Not Me.tcpListener.Server.Connected Then
Return
End If
End Try
End Sub
客户端写消息:
Public Function Write(value As String, encoding As Encoding) As Guid
Dim buffer As Byte() = encoding.GetBytes(value)
Return Me.Write(buffer)
End Function
Public Function Write(buffer As Byte()) As Guid
Dim guid__1 As Guid = Guid.NewGuid()
Dim networkStream As NetworkStream = Me.client.GetStream()
Dim result As IAsyncResult = networkStream.BeginWrite(buffer, 0, buffer.Length, Nothing, guid__1)
result.AsyncWaitHandle.WaitOne()
networkStream.EndWrite(result)
Return guid__1
End Function