2008年(148)
分类:
2008-06-03 22:06:16
在Vb.net 下实现在局域网内发信息,一般是采用socket , 以下是本人的一点点简单的实现实例,只是抛砖引玉,请大家指点:
以下是发送信息的过程:
Public Sub SendMessage(ByVal IP As String, ByVal SendMsg As String)
If IP <> "" Then
Dim tcpc As New System.Net.Sockets.TcpClient(IP, 5656)
Dim tcpStream As Net.Sockets.NetworkStream = tcpc.GetStream
Dim reqStream As New IO.StreamWriter(tcpStream)
reqStream.Write(SendMsg)
reqStream.Flush()
tcpStream.Close()
tcpc.Close()
End If
End Sub
以下为侦听及显示代码
Dim th As Threading.Thread
Dim tcpl As System.Net.Sockets.TcpListener
这是侦听过程
Private Sub MyListen()
Dim ipAddress As System.Net.IPAddress = System.Net.Dns.Resolve(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()
Dim MyBuffer(1024) As Byte
Dim i As Integer
i = s.Receive(MyBuffer)
If i > 0 Then
Me.Show()
Dim lstrRec As String
lstrRec = System.Text.Encoding.UTF8.GetString(MyBuffer)
Me.Label1.Text = lstrRec
End If
End While
End Sub
在窗体一打开是就开始一个侦听线程:
Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
th = New System.Threading.Thread(New System.Threading.ThreadStart(AddressOf MyListen))
th.Start()
End Sub