请帮助..我正在开发一个应用程序,它必须是Socket Server才能接收某些消息,但是我必须对客户端进行响应。到目前为止,我可以从客户端收到第一条消息,但是现在我不知道如何发送回复。我在这里找到了一些不同的示例,但是任何示例都对我有用。让我展示我的SockerServerClass代码的一部分:
Public Event MessageReceived(sendre As WinSockServer, clientSocket As TcpClient, Data As String)
Public Sub StopServer()
isListening = False
End Sub
Public Sub InitServer()
Try
oLog.i("[" & DateTime.Now & "] Iniciating Server ...")
tcpLsn = New TcpListener(serverIP, serverPort)
tcpLsn.Start()
tcpThd = New Thread(New ThreadStart(AddressOf Listening))
'tcpThd.IsBackground = True
tcpThd.Start()
Catch ex As Exception
oLog.e("[" & DateTime.Now & "][ERROR InitServer] " & ex.Message)
End Try
End Sub
Public Function Listening() As Boolean
Dim booResult As Boolean = False
oLog.i("[" & DateTime.Now & "] Iniciating Listening ...")
Do Until isListening = False
If tcpLsn.Pending Then
client = tcpLsn.AcceptTcpClient
clientData = New StreamReader(client.GetStream)
booResult = True
End If
Try
RaiseEvent MessageReceived(Me, client, clientData.ReadToEnd)
Catch ex As Exception
'vs oLog.e("[" & DateTime.Now & "][ERROR Listening] " & ex.Message)
End Try
Thread.Sleep(50)
Loop
Return booResult
End Function
**' This is the Method used to send a response to the Client
Public Sub SendData(ByVal DatoSnd As String, clientS As TcpClient)
Dim aSnd() As Byte = Encoding.UTF8.GetBytes(DatoSnd)
'Dim stream As NetworkStream
Dim streamW As StreamWriter
Try
'tcpLsn.Server.Send(aSnd)
streamW = New StreamWriter(clientS.GetStream)
'stream = client.GetStream()
'stream.Write(aSnd, 0, aSnd.Length)
streamW.Write(DatoSnd)
'streamW.Flush()
'stream.Close()
streamW.Close()
Catch exSocket As SocketException
oLog.e("[" & DateTime.Now & "][SOCKET ERROR SendData] " & exSocket.Message)
Catch ex As Exception
oLog.e("[" & DateTime.Now & "][ERROR SendData] " & ex.Message)
End Try
End Sub**
当接收到一条消息时,将调用Event MessageReceived事件,然后从那里尝试将响应发送给客户端
Private Sub oSocReturnCheck_MessageReceived(oSrv As WinSockServer, clientS As TcpClient, MsgData As String) Handles oSocReturnCheck.MessageReceived
Dim dato As String
Dim oLogAux As New Logger.Logger
Try
dato = MsgData
lblAux.Text = dato
dato = lblAux.Text
If Trim(dato) <> "" Then
**Me.oSocReturnCheck.SendData("A", clientS)
'oSrv.SendData("A", clientS)**
oLogAux.i("[" & DateTime.Now & "][HB_CONFIRM] " & MsgData)
Else
oLogAux.i("[" & DateTime.Now & "][HB_CONFIRM_EMPTY]")
End If
Catch ex As Exception
End Try
End Sub