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?
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.
Related
I have the following function to send and receive data it works OK for short strings like 150 bytes, but with a string of 2500 bytes it get stuck.
I tried to send some data with HTWin and nothing get the other end of the net.
So receiver on the other end never get even a character.
I tried also with the old Hyperterminal with same result.
Private Function SendReport(ByVal Msg As String, ByVal Host As String, ByVal Port As String) As String
Try
Dim Tx As New TcpClient()
Dim stream As NetworkStream = Nothing
Dim CloseStream As Boolean = False
Dim LingerMode As New LingerOption(True, 5)
' String to store the response ASCII representation.
Dim responseData As [String] = [String].Empty
Tx.NoDelay = True
Tx.LingerState = LingerMode
Tx.SendTimeout = 10000
Tx.ReceiveTimeout = 10000
Tx.Connect(Host, Port)
' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(Msg)
' Get a client stream for reading and writing.
' Stream stream = client.GetStream();
stream = Tx.GetStream()
CloseStream = True
'stream.WriteTimeout = 100
' Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length)
'Tx.Connected
' Receive the TcpServer.response.
' Buffer to store the response bytes.
data = New [Byte](256) {}
' Read the first batch of the TcpServer response bytes.
Dim bytes As Int32 = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
If CloseStream = True Then
stream.Close()
End If
Tx.Close()
Return responseData
Catch ex As Exception
WriteRTBLog(ex.Message, Color.Red)
WriteRTBLog(ex.StackTrace, Color.DarkRed)
Return "Error"
End Try
End Function
If I split the big string into smaller one and call this function over and over all the data reach the other end.
Also, I need to get an ACK packet that is big too and the code must wait for and special character that indicates the end.
I was thinking in to create a Thread with a TcpListener but, Is possible to have a TcpListener in the same port of a TcpClient?
The whole idea is to send a big string that is separated by an special character and finished with another special character.
The other end receive the data, split the string using the first special character and send one ACK by every item in the split function.
And in the last ACK send the second special character to indicate the end of the communication, so my application can process the received data properly.
I think I'm drowning in a glass of water.
I have problem about socket to send multiple hex in one send to socket
Here the detail :
Private Sub sendACK()
Dim msgACK As String
Dim sendBytes As Byte()
tmpStr = ""
list.Clear()
msgACK = "33CC"
For j = 1 To Len(msgACK)
list.Add(Mid(msgACK, j, 2))
j += 1
Next
For Each tmpStr In list
sendBytes = HexToBytes(tmpStr)
clientSocket.BeginSend(sendBytes, 0, sendBytes.Length, SocketFlags.None, New System.AsyncCallback(AddressOf OnSend), clientSocket)
Next
End Sub
Public Function HexToBytes(ByVal s As String) As Byte()
Dim bytes As String() = s.Split(" "c)
Dim retval(bytes.Length - 1) As Byte
For ix As Integer = 0 To bytes.Length - 1
retval(ix) = Byte.Parse(bytes(ix), System.Globalization.NumberStyles.HexNumber)
Next
Return retval
End Function
Private Sub OnSend(ByVal ar As IAsyncResult)
clientSocket = ar.AsyncState
clientSocket.EndSend(ar)
Thread.Sleep(100)
End Sub
==> List as arraylist
That code will be result :
Socket send 33
end send
Socket send CC
end send
============================
The program should be sending in one time like this :
Socket send 33 CC
end send
============================
is there any idea about convert string "33CC" into byte and then that program just sending 1 time in outter "for each" ?
thanks for reading and answering....
GBU
Your assumption is incorrect. It does indeed send both bytes at once. You are only calling BeginSend once and you are giving it both bytes, so if it is receiving them at all on the other end, then it is indeed sending them. In fact, there is no difference at all between sending them individually or sending them together. Since the socket works as a stream, the length of time between each byte being sent is largely irrelevant. There will be no way on the receiving end to know whether the two bytes were sent together or separately. All the receiving end will know is that the two bytes were sent in that order. If you think they are being sent as two separate "sends" on the receiving end, it sounds like you are making some invalid assumptions about how to read the data from the socket.
However, I should mention that the way you are sending the bytes, by first creating a hex string and then parsing it, is a bit silly. If you need to parse it as a string, because you are reading the hex values from a text file, or something, that's fine, but otherwise, you should just use hex byte literals in your code rather than strings, for instance:
Dim sendBytes As Byte() = {&H33, &HCC}
I'm coding an ascynchronous socket client for transferring files (following this Microsoft article) and notice that using BeginReceive corrupts the transfer because it adds a single Null character/chr(0) at the end of each packet. What could be causing this issue? I thought it might be the sending side, but I tested it with SendFile and had the same result.
In the Microsoft article it converts the bytes to an ASCII string and appends it to a StringBuilder. I want to save the bytes on-the-fly, so I barely modified the ReceiveCallback like so:
Private Shared Sub ReceiveCallback(ByVal ar As IAsyncResult)
Dim state As StateObject = CType(ar.AsyncState, StateObject)
Dim client As Socket = state.workSocket
Dim bytesRead As Integer = client.EndReceive(ar)
If bytesRead > 0 Then
FileIO.FileSystem.WriteAllBytes(Application.StartupPath & "\test.exe", state.buffer, True)
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state)
Else
receiveDone.Set()
End If
End Sub
The problem is a misconception on how Receive, or BeginReceive & EndReceive work.
When you call Receive and give it a buffer and a size, you are specifying the maximum amount of data to receive. It is the bytesRead that tells you how much you actually received. You need to only write that number of bytes to your output file, as only that portion of your buffer was populated with data.
See here for more details:
http://msdn.microsoft.com/en-us/library/w3xtz6a5
Here's the code on the sending side of my sockets:
Private Sub Send(ByRef Buffer() As Byte)
Dim obj_StateObject As New StateObject
obj_StateObject.WorkSocket = m_tmpSocket
m_tmpSocket.BeginSend(Buffer, 0, Buffer.Length, SocketFlags.None, New AsyncCallback(AddressOf OnClientSendComplete), obj_StateObject)
End Sub
Private Sub OnClientSendComplete(ByVal ar As IAsyncResult)
Dim obj_SocketState As StateObject = CType(ar.AsyncState, StateObject)
Dim obj_Socket As Socket = obj_SocketState.WorkSocket
End Sub
Here's the receiving code:
Private Sub OnServerDataArrival(ByVal ar As IAsyncResult)
Dim obj_SocketState As StateObject = CType(ar.AsyncState, StateObject)
Dim obj_Socket As Socket = obj_SocketState.WorkSocket
Dim BytesRead As Integer = obj_Socket.EndReceive(ar)
If (BytesRead > 0) Then
Dim TempLength As Integer = BitConverter.ToInt32(obj_SocketState.Buffer, 0) - 4
Dim TempBuffer(TempLength - 1) As Byte
Array.Copy(obj_SocketState.Buffer, 4, TempBuffer, 0, TempLength)
RaiseEvent ServerDataArrival(TMP_ID, TempBuffer)
End If
obj_Socket.BeginReceive(obj_SocketState.Buffer, 0, obj_SocketState.BufferSize, 0, New AsyncCallback(AddressOf OnServerDataArrival), obj_SocketState)
End Sub
I can send and receive data just fine usually. For instance, I can send a 10 byte buffer across with a button click and there are no problems.
However, if I set that button to call a function that will loop the sending of the 10 byte buffer 10 times, I will not receive about 8 of the buffers on average.
What is causing this? The sending code is executed 10 times, but the OnServerDataArrival function is only executed 2 times.
It is not clear from the code you've provided, but my guess is that you are transmitting the data using TCP (as opposed to UDP). If this is true, you shouldn't expect the send count to match the receive count. If you want that behavior, use UDP instead of TCP.
When using TCP, the data is typically buffered on the send side until a "sufficient" amount of data is ready to be sent. This usually helps improve the overall efficiency of the transmission, especially when sending messages as small as 10 bytes at a time. On the receive side, each read of the TCP socket reads all of the data from the socket's receive buffer up to the size of the buffer you provide. So if 8 of your 10 byte "messages" have been received, the next read from the socket will pull all that data into your buffer (providing it's big enough). You will need to parse your buffer to extract each message from the stream of bytes. Sending the size of the message, as you appear to be doing, will help you do this.
I need to store the first byte of data read from the network stream as a string, so I can call it back later.
prinf(" While 1
Dim tcpListener As New TcpListener(IPAddress.Any, 80) ' Listen to port given
Console.WriteLine("Waiting for connection...")
tcpListener.Start()
'Accept the pending client connection and return 'a TcpClient initialized for communication.
Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
Console.WriteLine("Connection accepted.")
' Get the stream
Dim networkStream As NetworkStream = tcpClient.GetStream()
' Read the stream into a byte array
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
' Return the data received from the client to the console.
Dim clientdata As String = Encoding.ASCII.GetString(bytes)
Console.WriteLine(("Client Sent: " + clientdata))
' Return the data received from the client to the console.
Dim responseString As String = "Hello"
'Dim chat_name As String = "Name"
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
networkStream.Write(sendBytes, 0, sendBytes.Length)
Console.WriteLine(("Response: " + responseString))
tcpClient.Close() 'Close TcpListener and TcpClient
tcpListener.Stop()
End While");
Thats my server ^ everything works fine, but I need the 1st piece of data read to be stored, such as if I get "Name" it should be stored in an array
Thanks
You'll need to define exactly what you mean by "1st piece of data" - is this data delimited in some form (like HTTP headers - key/value pairs are delimited by carriage-return line-feed)? Length-prefixed (like HTTP bodies when the Content-Length header is specified)? You almost certainly don't just want the first byte.
If you were hoping to just send the name and then send something else, without any indication of the fact that they're different bits of data, you're going to be disappointed. Streams are just sequences of bytes - there's nothing (built-in) to say "read what the client sent in their first API call".
This should work:
Dim strFirstByte as string = vbNullString
While 1
' ... Your code ...
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
If strFirstByte = vbNullString Then strFirstByte = bytes(0).ToString("X2")
' ... The rest of your code ...
End While