Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I need to create a TCP server that connects to a client on the same machine.
Client sends a string formatted as
minuted:secondes
for example:
10:25
.
The server receives the
time
string and starts to count down from it down to
00:00
I got it "working" but it crashes after some time running.
I press a label to start the server, run
timer1
to receive and update the
time
strings and
timer2
to create the count down.
The problem is with
timer1
but, I'm not sure how to solve it.
If I use:
MsgBox(ex.Message)
in the
Catch
block, I get the message:
A non-blocking socket operation could not be completed immediately
I do not know what it means.
Here are the
Project files
, and this is my code:
Imports System.Net
Imports System.Net.Sockets
Public Class Form1
Dim TCPServer As Socket
Dim server As TcpListener
Dim sec As Integer
Dim min As Integer
Private Sub Label3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label3.Click
Call TCPclient()
End Sub
Private Sub TCPclient()
server = New TcpListener(IPAddress.Parse("127.0.0.1"), 1234)
server.Start()
TCPServer = server.AcceptSocket()
TCPServer.Blocking = False
Timer1.Start()
Catch ex As Exception
End Try
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim rcvbytes(TCPServer.ReceiveBufferSize) As Byte
TCPServer.Receive(rcvbytes)
Dim mensage = System.Text.Encoding.ASCII.GetString(rcvbytes)
If mensage <> "0" Then
sec = mensage.Substring(3, 2)
min = mensage.Substring(0, 2)
Timer2.Start()
End If
Catch ex As Exception
End Try
End Sub
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
sec -= 1
If sec = 0 Then
min -= 1
sec = 60
End If
Label1.Text = min & " min" & ":" & sec & " sec"
If min = "-1" And sec = "60" Then
Label1.Text = "0 min:0 sec"
Timer2.Stop()
End If
Catch ex As Exception
End Try
End Sub
End Class
–
The issue arises in Timer1_Tick at
TCPServer.Receive(rcvbytes)
when you try to read but there are no bytes available.
You can avoid this simply checking for no bytes available at the beginning of Timer1_Tick function:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If (TCPServer.Available = 0) Then
Return
End If
Dim rcvbytes(TCPServer.ReceiveBufferSize) As Byte
Hope this helps
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.