前端之家收集整理的这篇文章主要介绍了
vb socket通信,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Imports System.Text
Class MainWindow
Dim tcpl As System.Net.Sockets.TcpListener
Dim socketList As ArrayList = New ArrayList
Private Sub Button1_Click(sender As System.Object,e As System.Windows.RoutedEventArgs) Handles Button1.Click
Dim XC_2 As System.Threading.Thread = New System.Threading.Thread(AddressOf SendMessage)
XC_2.Start()
End Sub
Private Sub Button2_Click(sender As System.Object,e As System.Windows.RoutedEventArgs) Handles Button2.Click
Dim XC_1 As System.Threading.Thread = New System.Threading.Thread(AddressOf MyListen)
XC_1.Start()
End Sub
Public Sub SendMessage()
Try
Dim tcpc As New System.Net.Sockets.TcpClient
tcpc.Connect("192.168.1.102",5656)
Dim tcpStream As Net.Sockets.NetworkStream = tcpc.GetStream
Dim data(1024) As Byte
Dim ss As String
While True
tcpStream.Read(data,data.Length)
ss = Encoding.ASCII.GetString(data)
ss = ss + ""
End While
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
Public Sub MyListen()
Try
Dim ipAddress As System.Net.IPAddress = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(0)
tcpl = New System.Net.Sockets.TcpListener(ipAddress,5656)
tcpl.Start()
While True
Dim s As System.Net.Sockets.Socket = tcpl.AcceptSocket()
socketList.Add(s)
Dim MyBuffer(1024) As Byte
Dim i As Integer
i = s.Receive(MyBuffer)
If i > 0 Then
Dim j As Integer
Dim ss As String
ss += Encoding.ASCII.GetString(MyBuffer)
End If
's.Send(MyBuffer)
End While
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
Private Sub Button3_Click(sender As System.Object,e As System.Windows.RoutedEventArgs) Handles Button3.Click
Dim socket As System.Net.Sockets.Socket = socketList(0)
Dim b As Byte()
b = System.Text.Encoding.ASCII.GetBytes("ssss")
socket.Send(b)
End Sub
End Class