2010年12月7日 星期二

vbnet socket 實例

服务端
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Public Class Form1
Dim s As Socket
Dim t As Thread

Delegate Sub setTextGetBack(ByVal arg1 As Integer, ByVal arg2 As Byte()) ''声明委托,异步调用

Private Sub setText(ByVal arg1 As Integer, ByVal arg2 As Byte())
If Me.ListBox1.InvokeRequired Then
Dim stg As setTextGetBack = New setTextGetBack(AddressOf setText)
Me.Invoke(stg, New Object() {arg1, arg2})
Else
Me.ListBox1.Items.Insert(arg1, Encoding.Unicode.GetString(arg2))
End If

End Sub

Public Sub waitData()
s = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '‘声明一个socket,使用tcp协议
Dim localEndPoint As New IPEndPoint(IPAddress.Parse("172.17.53.90"), 1024)
s.Bind(localEndPoint) '‘绑定到一台服务器
s.Listen(100) '‘侦听,最多可以侦听100连接

While True
Dim bytes(1024) As Byte '‘用来存储接收的数据字节
Dim ss As Socket = s.Accept() '‘若接收到,则创建一个新的socket与之连接
ss.Receive(bytes) '‘接收数据
setText(0, bytes) '‘处理接收到的数据
End While

End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
t = New Thread(AddressOf waitData)
t.Start()
Dim bytes(1024) As Byte
bytes = Encoding.Unicode.GetBytes("~~~~~~~~~~~~~~~~服务器开始启动~~~~~~~~~~~~~~~~")
Button1.Enabled = False
setText(0, bytes)
Try


's.Close()
't.Abort()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "错误提示")
Finally

End Try
End Sub

Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
Try

Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "错误提示")
Finally
s.Close() '‘关闭socket
t.Abort() ''中止线程
End Try
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
s.Close()
t.Abort()
Button1.Enabled = True
Button2.Enabled = False
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "错误提示")
End Try

End Sub
End Class


客户端
Imports System.Threading
Imports System.Text
Imports System.Net
Imports System.Net.Sockets
Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim s As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim endPint As IPEndPoint = New IPEndPoint(IPAddress.Parse("172.17.53.90"), 1024)
s.Connect(endPint)
s.Send(Encoding.Unicode.GetBytes(TextBox1.Text))
s.Close()
Catch ex As Exception

End Try
End Sub
End Class

沒有留言:

張貼留言