我有以下这些行使用socket
发送字节Dim server As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim myIp As IPAddress = IPAddress.Parse("myIP")
Dim ip As New IPEndPoint(myIp, Int32.Parse("myPort"))
server.Connect(ip)
server.Send(Encoding.UTF8.GetBytes("Halo")
这些是我用来接收的行
Dim data(255) As Byte
Dim bytesReceived As Integer = socket.Receive(buffer)
Dim stringData As String = Encoding.UTF8.GetString(data)
我的问题:
在代码中,我应该检索" Halo"。相反,我一直在接受......" []"。有人可以就此提出建议吗?
答案 0 :(得分:2)
要在套接字上接收数据,您需要使用Socket.Receive
方法。以下是您需要做的一个示例:
'Dim sock As Socket
Dim buffer(255) As Byte 'the data will be stored here
Dim bytesReceived As Integer = socket.Receive(buffer) 'will be used to see how many bytes were received
'not all bytes in the buffer contain data, so only use the number equal to the number received
Dim result As String = Encoding.UTF8.GetString(buffer, 0, bytesReceived)
我建议使用更大的缓冲区,例如4096。 http://msdn.microsoft.com/en-us/library/w89fhyex.aspx包含一些同步和异步套接字示例。