各位老大,小弟初學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
uj5u.com熱心網友回復:
為什么不用WinScok控制元件呢?uj5u.com熱心網友回復:
vb.net么?用多執行緒吧.
把監聽while放sub里
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/81829.html
標籤:網絡編程
上一篇:求助:VB代碼實作打開我的電腦
下一篇:通信程式,用的什么校驗方法
