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

zhoubapi3 2016-01-03 07:47:19
各位老大,小弟初学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
...全文
453 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
一笑拔剑 2016-01-07
  • 打赏
  • 举报
回复
vb.net么? 用多线程吧. 把监听while放sub里
一笑拔剑 2016-01-07
  • 打赏
  • 举报
回复
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim t1 As Threading.Thread
        Dim t2 As Threading.Thread
        t1 = New Threading.Thread(AddressOf 你的sub)
        t2 = New Threading.Thread(AddressOf 你的sub)
        t1.Start()
        t2.Start()
    End Sub
赵4老师 2016-01-05
  • 打赏
  • 举报
回复
为什么不用WinScok控件呢?

1,502

社区成员

发帖
与我相关
我的任务
社区描述
VB 网络编程
社区管理员
  • 网络编程
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧