Dim th as System.Threading.Thread th = New System.Threading.Thread(Addressof 方法名1) th.start()
Delegate Sub DelegateHandler(ByVal 参数 as String) '声明一个委托 private Sub 方法名1() dim dh as DelegateHandler = New DelegateHandler(AddressOf 方法名2) me.invoke(dh, new Object()...{"value"}) End Sub
private Sub 方法名2(ByVal str as String) '被委托给的方法 ,处理委托后的数据
'声明一个线程 Dim t As System.Threading.Thread t = New Thread(AddressOf WaitData) t.Start()
Dim s As Socket Public Sub WaitData()Sub WaitData() s = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) Dim localEndPoint As New IPEndPoint(IPAddress.Parse("127.0.0.1"), 1024) s.Bind(localEndPoint) s.Listen(100) Me.dealData(s) End Sub
Private Sub DealData()Sub DealData(ByRef sock As Socket) While (True) Dim bytes As Byte() = New Byte(1024) {} Dim ss As Socket = s.Accept() i = ss.Receive(bytes) Dim valstr As String = Encoding.Default.GetString(bytes, 0, i) '处理接收到的数据 '见第二步线程与委托技术
'发送回数据 ss.Send(Encoding.Default.GetBytes("已收到!!Love you")) '发回数据 End While End Sub
(2) 客户端
只要求连接到服务器端,然后就Send数据,同时可以Receive数据。示例代码如下:
Try Dim bytes As Byte() = New Byte(1024) {} s = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) Dim localEndPoint As New IPEndPoint(IPAddress.Parse("127.0.0.1"), 1024) s.Connect(localEndPoint)
Delegate Sub DelegateHandler()Sub DelegateHandler(ByVal str As String) '声明一个委托 Dim dh As DelegateHandler = New DelegateHandler(AddressOf 方法名) 'New 出一个委托并指定委托方法 Me.invoke(dh, New Object(){"传递的参数"}) '调用invoke方法
Private Sub 方法名()Sub 方法名(ByVal str As String) '处理委托的数据str