上面是服务端
以下是客户端
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Public Class SynchronousSocketClient
Public Shared Sub Main()
' Data buffer for incoming data.
Dim bytes(1024) As Byte
' Connect to a remote device.
' Establish the remote endpoint for the socket.
' This example uses port 11000 on the local computer.
Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName())
Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
Dim remoteEP As New IPEndPoint(ipAddress, 11000)
' Create a TCP/IP socket.
Dim sender As New Socket(AddressFamily.InterNetwork, _
SocketType.Stream, ProtocolType.Tcp)
' Connect the socket to the remote endpoint.
sender.Connect(remoteEP)
Console.WriteLine("Socket connected to {0}", _
sender.RemoteEndPoint.ToString())
' Encode the data string into a byte array.
Dim msg As Byte() = _
Encoding.ASCII.GetBytes("This is a test<EOF>")
' Send the data through the socket.
Dim bytesSent As Integer = sender.Send(msg)
' Receive the response from the remote device.
Dim bytesRec As Integer = sender.Receive(bytes)
Console.WriteLine("Echoed test = {0}", _
Encoding.ASCII.GetString(bytes, 0, bytesRec))
' Release the socket.
sender.Shutdown(SocketShutdown.Both)
sender.Close()
End Sub
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports Microsoft.VisualBasic
Public Class SynchronousSocketListener
' Incoming data from the client.
Public Shared data As String = Nothing
Public Shared Sub Main()
' Data buffer for incoming data.
Dim bytes() As Byte = New [Byte](1024) {}
' Establish the local endpoint for the socket.
' Dns.GetHostName returns the name of the
' host running the application.
Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName())
Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
Dim localEndPoint As New IPEndPoint(ipAddress, 11000)
' Create a TCP/IP socket.
Dim listener As New Socket(AddressFamily.InterNetwork, _
SocketType.Stream, ProtocolType.Tcp)
' Bind the socket to the local endpoint and
' listen for incoming connections.
listener.Bind(localEndPoint)
listener.Listen(10)
' Start listening for connections.
While True
Console.WriteLine("Waiting for a connection...")
' Program is suspended while waiting for an incoming connection.
Dim handler As Socket = listener.Accept()
data = Nothing
' An incoming connection needs to be processed.
While True
bytes = New Byte(1024) {}
Dim bytesRec As Integer = handler.Receive(bytes)
data += Encoding.ASCII.GetString(bytes, 0, bytesRec)
If data.IndexOf("<EOF>") > -1 Then
Exit While
End If
End While
' Show the data on the console.
Console.WriteLine("Text received : {0}", data)
' Echo the data back to the client.
Dim msg As Byte() = Encoding.ASCII.GetBytes(data)
handler.Send(msg)
handler.Shutdown(SocketShutdown.Both)
handler.Close()
End While
End Sub