从网上甚至MSDN上找的关于TcpClient的代码大多都是非常简单让你无法改造或者C#代码直接转换不成VB的,今天就非常直白的把我的代码写出来以便初学VB的人使用TcpClient。
现在开始一步一步的来
【定义TcpClient】
Dim Client as New TcpClient()
Client.ReceiveBufferSize = 4095
【连接到指定主机】
Client.Connect(IPAddress.Parse("127.0.0.1"),888)
- 1
【判断连接状态】
Client.Connected=True
Client.Connected=False
’需要注释吗?
【发送数据代码】
Private Sub SendData(Client as TcpClient,Buffer as byte())
Client.Client.Send(buffer)
End Sub
- 3
【接收代码,不跨线程访问GUI控件】
' 【连接到指定的主机】代码后
If Client.Connected then
Dim t as new Thread(addressof DataListener)
t.start(Client)
Else
Msgbox("Error!“)
End if
'监听线程
Private Sub DataListener(Client as TcpClient)
Dim Buffer(4095) as byte
Dim RecLength as integer
Do Until StopFlag
'不再复述,详情
'http://blog.csdn.net/runplus/article/details/49019245
Loop
End Sub
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
【接收代码,跨线程代理访问GUI控件】
例:窗口有一Textbox(TextBox1),需要在接收到数据后在此显示内容
A.定义委托
Public Class Form1
紧接代码定义委托
Private Delegate Sub DelegateUpdateTextbox(Packet As Byte())
'........
End Class
- 3
- 4
- 5
B.创建委托实际过程
Private Sub UpdateTextbox(Packet as byte()
Textbox1.text=Text.Encoding.Utf8.GetString(Packet)
End Sub
- 3
C.调整DataListener过vb.net教程程
Private Sub DataListener(Client as TcpClient)
Dim TrdUpdateTextbox as new DelegateUpdatetextbox(AddressOf Updatetextbox)
Dim Buffer(4095) as byte
Dim RecLength as integer
Do Until StopFlag
'不再复述,详情
'http://blog.csdn.net/runplus/article/details/49019245
'上文中定义了Packet为接收到的数据,这里使用这个Byte()来委托更新
Me.BeginInvoke(TrdUpdateTextbox,Packet)
Loop
End Sub
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12