Imports System.Net
'Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Public Class Form1
Public Delegate Sub addtext(ByVal a As String)
Dim listener As New Sockets.Socket(Sockets.AddressFamily.InterNetwork, Sockets.SocketType.Stream,
Sockets.ProtocolType.Tcp)
Private Sub server_Click(sender As System.Object, e As System.EventArgs) Handles server.Click
Dim ipAddress1 As IPAddress = IPAddress.Parse("127.0.0.1")
Dim localEndPoint As New IPEndPoint(ipAddress1, 11000)
listener.Bind(localEndPoint)
listener.Listen(10)
Dim t1 As Thread = New Thread(AddressOf rec)
t1.Start()
End Sub
Sub rec()
Dim bytes() As Byte
Dim handler As Sockets.Socket = listener.Accept() '建立连接请求
Dim data As String = Nothing
bytes = New Byte(1024) {}
Dim bytesRec As Integer = handler.Receive(bytes) '接收数据
If bytesRec > 0 Then
data = Encoding.Unicode.GetString(bytes, 0, bytesRec)
addmess(data)
Else
Exit Sub
End If
handler.Shutdown(Sockets.SocketShutdown.Both)
handler.Close()
End Sub
Sub addmess(ByVal a As String)
If TextBox1.InvokeRequired Then
Dim d As addtext = New addtext(AddressOf addmess)
TextBox1.Invoke(d, a)
Else
TextBox1.Text = a
End If
End Sub
Private Sub client_Click(sender As System.Object, e As System.EventArgs) Handles client.Click
Dim bytes(1024) As Byte '声明字节数组
Dim sender1 As New Sockets.Socket(Sockets.AddressFamily.InterNetwork, Sockets.SocketType.Stream, Sockets.ProtocolType.Tcp)
'初始化socket
Dim msg As Byte() = Encoding.Unicode.GetBytes("TextBox1.Text")
'对发送的数据进行编码
'***************************
'指定ip和端口
Dim ipAddress1 As IPAddress = IPAddress.Parse("127.0.0.1")
Dim ipe As New IPEndPoint(ipAddress1, 11000)
'**********************
sender1.Connect(ipe) '建立连接
Dim bytesSent As Integer = sender1.Send(msg) '发送数据
'关闭socket
sender1.Shutdown(Sockets.SocketShutdown.Both)
sender1.Close()
End Sub
End Class