Este artigo passo a passo descreve como programa Microsoft interface de sockets do Windows (Winsock) e as ligações de rede no Microsoft Visual Basic .NET ou no Microsoft Visual Basic 2005. No exemplo, uma aplicação de cliente de TCP (transporte Control Protocol) simples denominado TestTCPClient e uma aplicação de servidor TCP (escuta) simples denominado TestTCPServer utilizam a interface dos sockets do Windows para comunicar com outro de mensagens em fila.
Inicie o Microsoft Visual Studio .NET ou Microsoft Visual Basic 2005.
No menu ficheiro , clique em Novo e, em seguida, clique em projecto .
Em tipos de projecto , clique em projectos de Visual Basic .
Nota No Visual Studio 2005, clique em Visual Basic em tipos de projecto .
Em modelos , clique em consola aplicação .
Nome do projecto TestTCPClient e, em seguida, clique em ' OK ' .
Por predefinição, é criado Module1.vb.
Substituir o código de Module1.vb com o seguinte código:
Imports System.Net.Sockets
Imports System.Text
Class CTestTCPClient
Shared Sub Main()
Dim tcpClient As New System.Net.Sockets.TcpClient
'"Localhost" string is used when the client and the listener are on the same computer.
'If the listener is listening at a computer that is different from the client, provide the host name of the computer
'where the listener is listening.
tcpClient.Connect("Localhost", 8000)
Dim networkStream As NetworkStream = tcpClient.GetStream()
If networkStream.CanWrite And networkStream.CanRead Then
' Do a simple write.
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Is anybody listening...")
networkStream.Write(sendBytes, 0, sendBytes.Length)
' Read the NetworkStream into a byte buffer.
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
' Output the data received from the host to the console.
Dim returndata As String = Encoding.ASCII.GetString(bytes)
Console.WriteLine(("TCP Server returned: " + returndata))
Else
If Not networkStream.CanRead Then
Console.WriteLine("Could not write data to data stream")
tcpClient.Close()
Else
If Not networkStream.CanWrite Then
Console.WriteLine("Could not read data from data stream")
tcpClient.Close()
End If
End If
End If
' Pause to let the user view the console output.
Console.ReadLine()
End Sub
End Class
Console.ReadLine() End Sub End classe este código cria uma nova instância da classe tcpClient , chama o ligar método e, em seguida, o acesso de ganhos à sequência de dados subjacente utilizando o método GetStream() da classe NetworkStream . A mensagem é convertida para uma matriz de bytes enviada para o fluxo de dados e, em seguida, ler o fluxo de dados para a resposta da aplicação de servidor do TCP (escuta).
Criar um servidor TCP aplicação (serviço de escuta)
Inicie o Microsoft Visual Studio .NET ou Microsoft Visual Studio 2005.
No menu ficheiro , clique em Novo e, em seguida, clique em projecto .
Em tipos de projecto , clique em projectos de Visual Basic .
Nota No Visual Studio 2005, clique em Visual Basic em tipos de projecto .
Em modelos , clique em consola aplicação .
Nome do projecto TestTCPServer e, em seguida, clique em ' OK ' .
Por predefinição, é criado Moudle1.vb.
Substituir o seguinte código com o código dos Module1.vb:
Imports System.Net.Sockets
Imports System.net
Imports System.Text
Imports System.Net.DnsPermissionAttribute
Imports System.Security.Permissions
'DnsPermissionAttribute specifies permission to request information from Domain Name Servers.
<DnsPermissionAttribute(SecurityAction.Demand, Unrestricted:=True)> Class CTestTCPServer
Shared Sub Main()
'Listening must be on the same port that the client is connected on.
Const portNumber As Integer = 8000
'"Localhost" string is used when the client and the listener are on the same computer.
'If the listener is listening at a computer that is different from the client, then provide the host name of the computer
'where the listener is listening.
Dim tcpListener As New TcpListener(CType(Dns.Resolve("Localhost").AddressList(0), IPAddress), portNumber)
'Comment the previous line and uncomment the following line if you are using Visual Basic .NET (2003).
'Dim tcpListener As New TcpListener(portNumber)
tcpListener.Start()
Console.WriteLine("TCP Server is up and waiting for Client connection...")
Try
''Accept the pending client connection and return a TcpClient for communication.
Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
Console.WriteLine("Connection accepted.")
' Get the data stream.
Dim networkStream As NetworkStream = tcpClient.GetStream()
' Read the data stream into a byte array.
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
' Return the data received from the client to the console.
Dim clientdata As String = Encoding.ASCII.GetString(bytes)
Console.WriteLine(("Client sent: " + clientdata))
Dim responseString As String = "Successfully connected to TCP server."
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
networkStream.Write(sendBytes, 0, sendBytes.Length)
Console.WriteLine(("Message Sent by TCP Server /> : " + responseString))
'Close TcpListener and TcpClient.
tcpClient.Close()
tcpListener.Stop()
Console.WriteLine("Exit")
Console.ReadLine()
Catch e As Exception
Console.WriteLine(e.ToString())
Console.ReadLine()
End Try
End Sub
End Class
a aplicação de TestTCPServer cria uma nova instância da classe tcpListener na porta, chama o método Start() e, em seguida, aceita o pedido de cliente pendentes utilizando o método AcceptTcpClient() . O método AcceptTcpClient() devolve o objecto de tcpClient que pode utilizar para enviar e receber dados.
Para testar o exemplo, criar e executar a aplicação de TestTCPServer e, em seguida, criar e executar a aplicação de TestTCPClient. As mensagens na janela da consola indicam que o TestTCPClient aplicação e a aplicação de TestTCPServer estão a comunicar utilizando a interface de sockets do Windows.
IMPORTANTE: Este artigo foi traduzido por um sistema de tradução automática (também designado por Machine translation ou MT), não tendo sido portanto revisto ou traduzido por humanos. A Microsoft tem artigos traduzidos por aplicações (MT) e artigos traduzidos por tradutores profissionais. O objectivo é simples: oferecer em Português a totalidade dos artigos existentes na base de dados do suporte. Sabemos no entanto que a tradução automática não é sempre perfeita. Esta pode conter erros de vocabulário, sintaxe ou gramática? erros semelhantes aos que um estrangeiro realiza ao falar em Português. A Microsoft não é responsável por incoerências, erros ou estragos realizados na sequência da utilização dos artigos MT por parte dos nossos clientes. A Microsoft realiza actualizações frequentes ao software de tradução automática (MT). Pedíamos-lhe o favor de preencher o formulário existente no fundo desta página caso venha a encontrar erros neste artigo e tenha possibilidade de colaborar no processo de aperfeiçoamento desta ferramenta. Obrigado.
Clique aqui para ver a versão em Inglês deste artigo: 821768
(http://support.microsoft.com/kb/821768/en-us/
)