rofans91
rofans91

Reputation: 3010

.NET Socket Send & Receive Not Matching

I have these following lines to send bytes using 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")

These are the lines I use to receive

Dim data(255) As Byte

Dim bytesReceived As Integer = socket.Receive(buffer)

Dim stringData As String = Encoding.UTF8.GetString(data)

My problem:

As in the code, I am supposed to retrieved "Halo". Instead I keep receiving sth like "[]". Can someone give me advise on this?

Upvotes: 1

Views: 2811

Answers (1)

Timiz0r
Timiz0r

Reputation: 1324

In order to receive data on a socket, you need to use the Socket.Receive method. Here's an example of what you need to do:

'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)

I would recommend using a larger buffer, though, such as 4096. http://msdn.microsoft.com/en-us/library/w89fhyex.aspx contains a few synchronous and asynchronous socket examples.

Upvotes: 2

Related Questions