I am trying to communicate with an Arduino using an ethernet wired connection. I did that using python and C but now m getting difficulty doing the same with VB.net. Simply I am trying to send a UDP packet to Arduino using its IP address and port number and want the response to get back and show it in the textbox.
Imports System.Net
Imports System.Environment, System.Text.Encoding
Public Class udpWindow
Dim localIP As String = Dns.GetHostByName(Dns.GetHostName()).AddressList(0).ToString
Dim localPort As Integer = 5000
Dim publisher As New Sockets.UdpClient(0)
Dim subscriber As New Sockets.UdpClient(localPort)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
LocalIP_txt.Text = localIP
localPort_txt.Text = localPort
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Start.Click
publisher.Connect(ServerIP.Text, ServerPort.Text)
Dim sendbytes() As Byte = ASCII.GetBytes("0")
publisher.Send(sendbytes, sendbytes.Length)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
subscriber.Client.ReceiveTimeout = 100
subscriber.Client.Blocking = False
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Try
Dim ep As IPEndPoint = New IPEndPoint(0, localPort)
Dim recvbytes() As Byte = subscriber.Receive(ep)
'MsgBox("msg recieved")
rcvMsgs.Text = ASCII.GetString(recvbytes)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
Can anyone help me with a better alternative or with the correction? Thanx in advance as this is my first query over here so pardon for any improper mistake.
subscriber
's socket into non-blocking mode. TheReceive()
method does not work in non-blocking mode. The error you are getting is basically telling you that the socket returned aWSAEWOULDBLOCK
error when there is no data available to read. Use theBeginReceive()
orReceiveAsync()
method instead for non-blocking reads, and let the socket notify you when data is available, don't poll for itsubscriber.Available > 0
before callingsubscriber.Receive()
. Or, since you are using a timeout anyway, just have yourtry..catch
ignore anySocketException
whoseErrorCode
isWSAETIMEDOUT
(10060). Or, get rid of the timer and use a separate thread that callsReceive()
in a loop without a timeout.