请教程序如何同时处理多个TCP连接

zhoubapi3 zhoubapi3 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
各位老大,小弟初学VB,请多赐教:
环境:visual studio 2015, Visual Basic
参考程序:https://msdn.microsoft.com/zh-cn/library/system.net.sockets.tcplistener.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2
改造:把原来程序里边的try catch去掉了,程序由一个按钮控制启动
运行情况:程序基本成功,能够正确接受来自client端的请求并做出相应
问题:程序进入while语句后,其他什么事情都做不了,一门心思地在等待客户端的请求;甚至于我在程序界面做了一个退出按钮想退出程序也不行。
希望:程序在监听客户端请求的时候,也可以允许我做一些其它事情,必须在界面上做一些其它输入操作,允许我按界面上的按钮。

非常感谢各位大侠!

主程序如下:
      Dim server As TcpListener
server = Nothing

' Set the TcpListener on port 13000.
Dim port As Int32 = 13000
Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.1")
server = New TcpListener(localAddr, port)

' Start listening for client requests.
server.Start()

' Buffer for reading data
Dim bytes(1024) As Byte
Dim data As String = Nothing
While True
' Enter the listening loop.
MsgBox("Waiting for a connection...")
' Perform a blocking call to accept requests.
' You could also user server.AcceptSocket() here.
Dim client As TcpClient = server.AcceptTcpClient()
MsgBox("Connected!")
data = Nothing

' Get a stream object for reading and writing
Dim stream As NetworkStream = client.GetStream()
Dim i As Int32

' Loop to receive all the data sent by the client.
i = stream.Read(bytes, 0, bytes.Length)
While (i <> 0)
' Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
MsgBox("Received: " & data)
' Process the data sent by the client.
data = data.ToUpper()
Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(data)

' Send back a response.
stream.Write(msg, 0, msg.Length)
MsgBox("Sent: " & data)

i = stream.Read(bytes, 0, bytes.Length)

End While

' Shutdown and end connection
client.Close()


End While
...全文

相关推荐

评论 3
收藏 已收藏
分享
返回顶部
zhoubapi3
网络编程 1,502 成员 18,427 内容