Chinaunix首页 | 论坛 | 博客
  • 博客访问: 914758
  • 博文数量: 148
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 3920
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-30 18:17
文章分类

全部博文(148)

文章存档

2008年(148)

我的朋友

分类:

2008-06-03 22:06:16

vb.net下的socket编程  

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

阅读(2232) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~