Visual Basic è possibile creare applicazioni che comunicano con altri processi di named pipe. Named pipe deve essere creata in Windows 2000 o Windows NT; tuttavia, è possibile leggere e scrivere in pipe da qualsiasi piattaforma a 32 bit.
In questo articolo viene spiegato comunicazione client/server mediante un named pipe in Visual Basic.
In questo articolo, il processo di creazione di NamedPipe è denominato server e il processo di connessione alla named pipe viene chiamato il client.
Sono necessari sei passaggi alla creazione di un server di named pipe:
Creare un token di protezione per la pipe consentire l'accesso (per rendere disponibile a qualsiasi processo un named pipe creando un token di protezione con un discrezionale elenco DACL (Access Control) contenente le voci di zero).
Creare named pipe.
Chiamare ConnectNamedPipe per bloccare fino a quando un client si connette.
Chiamare il metodo ReadFile e/o WriteFile per comunicare attraverso la pipe.
Chiamare DisconnectNamedPipe è terminato il processo tramite la pipe.
Entrambi CloseHandle sulla named pipe o andare al passaggio 4.
Prevede tre passaggi per utilizzare un named pipe dal client named pipe:
Chiamare CreateFile per ottenere un handle al named pipe.
Chiamare il metodo ReadFile e/o WriteFile per comunicare attraverso la pipe.
Chiamare il filehandle creato in CreateFile CloseHandle.
In alternativa, è possibile chiamare CallNamedPipe, che esegue una singola transazione attraverso la pipe. CallNamedPipe apre la pipe, scrive, si legge, quindi viene chiusa la pipe. Si tratta di cosa è il client riportato di seguito.
Nell'esempio riportato di seguito viene illustrato come creare una named pipe server e client. Implementa solo le funzioni più rudimentale necessaria, con una minima quantità di controllo degli errori. Un programma completamente funzionante deve controllare i valori restituiti delle API che vengono chiamati, anziché supponendo che sono stati completati.
Named pipe server
Creare un nuovo progetto. In base all'impostazione predefinita, viene creato il progetto Form1.
Aggiungere il codice riportato di seguito al form:
Option Explicit
Private Const szPipeName = "\\.\pipe\bigtest"
Private Const BUFFSIZE = 20000
Private BigBuffer(BUFFSIZE) As Byte, pSD As Long
Private sa As SECURITY_ATTRIBUTES
Private hPipe As Long
Private Sub Form_Click()
Dim i As Long, dwOpenMode As Long, dwPipeMode As Long
Dim res As Long, nCount As Long, cbnCount As Long
For i = 0 To BUFFSIZE - 1 'Fill an array of numbers
BigBuffer(i) = i Mod 256
Next i
'Create the NULL security token for the pipe
pSD = GlobalAlloc(GPTR, SECURITY_DESCRIPTOR_MIN_LENGTH)
res = InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)
res = SetSecurityDescriptorDacl(pSD, -1, 0, 0)
sa.nLength = LenB(sa)
sa.lpSecurityDescriptor = pSD
sa.bInheritHandle = True
'Create the Named Pipe
dwOpenMode = PIPE_ACCESS_DUPLEX Or FILE_FLAG_WRITE_THROUGH
dwPipeMode = PIPE_WAIT Or PIPE_TYPE_MESSAGE Or PIPE_READMODE_MESSAGE
hPipe = CreateNamedPipe(szPipeName, dwOpenMode, dwPipeMode, _
10, 10000, 2000, 10000, sa)
Do 'Wait for a connection, block until a client connects
res = ConnectNamedPipe(hPipe, ByVal 0)
'Read/Write data over the pipe
cbnCount = 4
res = ReadFile(hPipe, nCount, LenB(nCount), cbnCount, ByVal 0)
If nCount <> 0 Then
If nCount > BUFFSIZE Then 'Client requested nCount bytes
nCount = BUFFSIZE 'but only send up to 20000 bytes
End If
'Write the number of bytes requested
res = WriteFile(hPipe, BigBuffer(0), nCount, cbnCount, ByVal 0)
'Make sure the write is finished
res = FlushFileBuffers(hPipe)
End If
'Disconnect the NamedPipe
res = DisconnectNamedPipe(hPipe)
Loop Until nCount = 0
'Close the pipe handle
CloseHandle hPipe
GlobalFree (pSD)
End
End Sub
Creare un nuovo modulo e aggiungere le seguenti dichiarazioni:
Option Explicit
Public Const FILE_ATTRIBUTE_NORMAL = &H80
Public Const FILE_FLAG_NO_BUFFERING = &H20000000
Public Const FILE_FLAG_WRITE_THROUGH = &H80000000
Public Const PIPE_ACCESS_DUPLEX = &H3
Public Const PIPE_READMODE_MESSAGE = &H2
Public Const PIPE_TYPE_MESSAGE = &H4
Public Const PIPE_WAIT = &H0
Public Const INVALID_HANDLE_VALUE = -1
Public Const SECURITY_DESCRIPTOR_MIN_LENGTH = (20)
Public Const SECURITY_DESCRIPTOR_REVISION = (1)
Type SECURITY_ATTRIBUTES
nLength As Long
lpSecurityDescriptor As Long
bInheritHandle As Long
End Type
Public Const GMEM_FIXED = &H0
Public Const GMEM_ZEROINIT = &H40
Public Const GPTR = (GMEM_FIXED Or GMEM_ZEROINIT)
Declare Function GlobalAlloc Lib "kernel32" ( _
ByVal wFlags As Long, ByVal dwBytes As Long) As Long
Declare Function GlobalFree Lib "kernel32" (ByVal hMem As Long) As Long
Declare Function CreateNamedPipe Lib "kernel32" Alias _
"CreateNamedPipeA" ( _
ByVal lpName As String, _
ByVal dwOpenMode As Long, _
ByVal dwPipeMode As Long, _
ByVal nMaxInstances As Long, _
ByVal nOutBufferSize As Long, _
ByVal nInBufferSize As Long, _
ByVal nDefaultTimeOut As Long, _
lpSecurityAttributes As Any) As Long
Declare Function InitializeSecurityDescriptor Lib "advapi32.dll" ( _
ByVal pSecurityDescriptor As Long, _
ByVal dwRevision As Long) As Long
Declare Function SetSecurityDescriptorDacl Lib "advapi32.dll" ( _
ByVal pSecurityDescriptor As Long, _
ByVal bDaclPresent As Long, _
ByVal pDacl As Long, _
ByVal bDaclDefaulted As Long) As Long
Declare Function ConnectNamedPipe Lib "kernel32" ( _
ByVal hNamedPipe As Long, _
lpOverlapped As Any) As Long
Declare Function DisconnectNamedPipe Lib "kernel32" ( _
ByVal hNamedPipe As Long) As Long
Declare Function WriteFile Lib "kernel32" ( _
ByVal hFile As Long, _
lpBuffer As Any, _
ByVal nNumberOfBytesToWrite As Long, _
lpNumberOfBytesWritten As Long, _
lpOverlapped As Any) As Long
Declare Function ReadFile Lib "kernel32" ( _
ByVal hFile As Long, _
lpBuffer As Any, _
ByVal nNumberOfBytesToRead As Long, _
lpNumberOfBytesRead As Long, _
lpOverlapped As Any) As Long
Declare Function FlushFileBuffers Lib "kernel32" ( _
ByVal hFile As Long) As Long
Declare Function CloseHandle Lib "kernel32" ( _
ByVal hObject As Long) As Long
Salvare il modulo.
Named pipe client
Creare un nuovo progetto. In base all'impostazione predefinita, viene creato il progetto Form1.
Aggiungere i seguenti controlli al form:
Type Name Caption/Default Value
---- ---- ---------------------
TextBox cbBytes 500
CommandButton cmdCallNamedPipe Call Named Pipe
TextBox txtReceive
Aggiungere il codice riportato di seguito al form:
Option Explicit
Private Const szPipeName = "\\.\pipe\bigtest", BUFFSIZE = 20000
Private Declare Function CallNamedPipe Lib "kernel32" Alias _
"CallNamedPipeA" ( _
ByVal lpNamedPipeName As String, _
lpInBuffer As Any, _
ByVal nInBufferSize As Long, _
lpOutBuffer As Any, _
ByVal nOutBufferSize As Long, _
lpBytesRead As Long, _
ByVal nTimeOut As Long) As Long
Private Sub cmdCallNamedPipe_Click()
Dim res As Long, myStr As String, i As Long, cbRead As Long
Dim numBytes As Long, bArray() As Byte, temp As String
numBytes = cbBytes.Text
If cbBytes.Text < 0 Then
MsgBox "Value must be at least 0.", vbOKOnly
Exit Sub
End If
If numBytes > BUFFSIZE Then
numBytes = BUFFSIZE
End If
ReDim bArray(numBytes) 'Build the return buffer
'Call CallNamedPipe to do the transaction all at once
res = CallNamedPipe(szPipeName, numBytes, LenB(numBytes), _
bArray(0), numBytes, _
cbRead, 30000) 'Wait up to 30 seconds for a response
If res > 0 Then
temp = Format(bArray(0), " 000")
For i = 1 To cbRead - 1
If (i Mod 16) = 0 Then temp = temp & vbCrLf
temp = temp & " " & Format(bArray(i), "000")
Next i
txtReceive.Text = temp
Else
MsgBox "Error number " & Err.LastDllError & _
" attempting to call CallNamedPipe.", vbOKOnly
End If
End Sub
Si noti che se il server è in esecuzione su un computer diverso da quello in cui il client è, è necessario modificare il '. ' nella variabile szPipeName al nome del computer server.
Salvare il modulo. Per verificare il codice sopra riportato, avviare il server e fare clic in un punto qualsiasi del form. L'applicazione server è ora il blocco e verrà visualizzato è bloccato, ma è effettivamente in attesa di al client di connettersi. Avviare l'applicazione client e scegliere "Chiamata named pipe". Il client deve inviare il valore 500 al server, che risponderà con 500 byte di dati. È possibile impostare il valore nella casella di testo cbBytes da 0 a 20000 byte. Per arrestare il server, è sufficiente inviare 0 (zero) dal client. Il client potrebbe ricevere un errore 233 (ERROR_PIPE_NOT_CONNECTED), ma questo è normale.
Un altro miglioramento a quello che può includere l'utilizzo di porte di completamento I/O e/o -blocco non di letture e scritture utilizzo I/O sovrapposte. È possibile trovare ulteriori informazioni su questi argomenti in Microsoft Platform SDK.
Sono disponibili diversi metodi InterProcess Communication (IPC) in Windows 2000, Windows NT e Windows 95 che consentono il trasferimento unidirezionale o bidirezionale dei dati tra più processi. Per un elenco completo di metodi di IPC disponibili su ogni piattaforma, vedere il seguente articolo della Microsoft Knowledge Base riportato di seguito:
Identificativo articolo: 177696 - Ultima modifica: lunedì 12 febbraio 2007 - Revisione: 2.4
Le informazioni in questo articolo si applicano a:
Microsoft Visual Basic 4.0 Professional Edition
Microsoft Visual Basic 5.0 Professional Edition
Microsoft Visual Basic 6.0 Professional Edition
Microsoft Visual Basic 4.0 Enterprise Edition
Microsoft Visual Basic 5.0 Enterprise Edition
Microsoft Visual Basic Enterprise Edition for Windows 6.0
Microsoft Windows NT 4.0
Microsoft Windows NT 3.51 Service Pack 5
Microsoft Windows NT 4.0
Microsoft Windows 98 Standard Edition
Microsoft Win32 Application Programming Interface
the operating system: Microsoft Windows 2000
Microsoft Windows 95
Microsoft Windows Millennium Edition
Chiavi:
kbmt kbapi kbhowto KB177696 KbMtit
Traduzione automatica articoli
Il presente articolo è stato tradotto tramite il software di traduzione automatica di Microsoft e non da una persona. Microsoft offre sia articoli tradotti da persone fisiche sia articoli tradotti automaticamente da un software, in modo da rendere disponibili tutti gli articoli presenti nella nostra Knowledge Base nella lingua madre dell?utente. Tuttavia, un articolo tradotto in modo automatico non è sempre perfetto. Potrebbe contenere errori di sintassi, di grammatica o di utilizzo dei vocaboli, più o meno allo stesso modo di come una persona straniera potrebbe commettere degli errori parlando una lingua che non è la sua. Microsoft non è responsabile di alcuna imprecisione, errore o danno cagionato da qualsiasi traduzione non corretta dei contenuti o dell?utilizzo degli stessi fatto dai propri clienti. Microsoft, inoltre, aggiorna frequentemente il software di traduzione automatica.
Clicca qui per visualizzare la versione originale in inglese dell?articolo: 177696
(http://support.microsoft.com/kb/177696/en-us/
)
LE INFORMAZIONI CONTENUTE NELLA MICROSOFT KNOWLEDGE BASE SONO FORNITE SENZA GARANZIA DI ALCUN TIPO, IMPLICITA OD ESPLICITA, COMPRESA QUELLA RIGUARDO ALLA COMMERCIALIZZAZIONE E/O COMPATIBILITA' IN IMPIEGHI PARTICOLARI. L'UTENTE SI ASSUME L'INTERA RESPONSABILITA' PER L'UTILIZZO DI QUESTE INFORMAZIONI. IN NESSUN CASO MICROSOFT CORPORATION E I SUOI FORNITORI SI RENDONO RESPONSABILI PER DANNI DIRETTI, INDIRETTI O ACCIDENTALI CHE POSSANO PROVOCARE PERDITA DI DENARO O DI DATI, ANCHE SE MICROSOFT O I SUOI FORNITORI FOSSERO STATI AVVISATI. IL DOCUMENTO PUO' ESSERE COPIATO E DISTRIBUITO ALLE SEGUENTI CONDIZIONI: 1) IL TESTO DEVE ESSERE COPIATO INTEGRALMENTE E TUTTE LE PAGINE DEVONO ESSERE INCLUSE. 2) I PROGRAMMI SE PRESENTI, DEVONO ESSERE COPIATI SENZA MODIFICHE, 3) IL DOCUMENTO DEVE ESSERE DISTRIBUITO INTERAMENTE IN OGNI SUA PARTE. 4) IL DOCUMENTO NON PUO' ESSERE DISTRIBUITO A SCOPO DI LUCRO.
Grazie. I commenti e suggerimenti forniti verranno utilizzati per migliorare la qualità dei contenuti di supporto tecnico. Per ulteriori opzioni di assistenza, visitare la home page del Supporto Tecnico Microsoft.