vb.net - How to politely stop a TcpListener? -
i have tcp server works ok need stop , threads in safe way. far research abort method not ok
i debugged and, when server started , have no connections, seems code halts on line
server = new tcplistener(ipaddress.any, port)
so when call stopserver error wsacancelblokingcall can't figured out how stops server.
here's code complete except starttcpclient data received.
#region "tcp receive variables" dim tcpopen boolean = false private server tcplistener = nothing private serverthread thread = nothing friend ackstring string = "" #end region #region "tcp" public sub stopserver() server.stop() serverthread.abort() tcpopen = false end sub public sub initserver(byval port integer) server = new tcplistener(ipaddress.any, port) serverthread = new thread(addressof connectionlistener) serverthread.isbackground = true serverthread.start() tcpopen = true end sub private sub connectionlistener() server.start() while true dim client tcpclient = server.accepttcpclient() dim t new thread(addressof starttcpclient) t.isbackground = true t.start(client) end while end sub #end region
edit: make changes in code , seem work need.
public sub stopserver() tcpopen = false server.stop() serverthread = nothing end sub private sub connectionlistener() server.start() while true if tcpopen if server.pending dim client tcpclient = server.accepttcpclient() dim t new thread(addressof starttcpclient) t.isbackground = true t.start(client) else system.threading.thread.sleep(10) end if else exit while end if end while end sub
the connection should closed client (not server).
the client should send application message server stop processing.
the server should stop processing
the server should perform begindisconnect
the server should send response client indicating connection can closed
the client should close connection.
the server when beingdisconnect occurs should close/dispose listener.
Comments
Post a Comment