Тока что зарегился - не успел прочесть всю БД форума - поэтому сорри, если повторяюсь... Я ищу на этот вопрос ответ уже пол года =)
Как работать с FTP - а именно класть туда файлы и считывать? Заранее благодарю =)
MSDN Library April 2000 писал(а):Visual Basic Concepts
Using the Internet Transfer Control
The Internet Transfer control implements two widely-used Internet protocols: the HyperText Transfer Protocol (HTTP) and the File Transfer Protocol (FTP). Using the Internet Transfer control, you can connect to any site that uses one of these protocols, and retrieve files using either the OpenURL or Execute method.
Possible Uses
To add an FTP browser to any application.
To create an application that automatically downloads files from a public FTP site.
To parse a World Wide Web site for graphics references and download the graphics only.
To present a custom display of dynamic data retrieved from a Web page.
Basic Operation
The functionality of the Internet Transfer control depends on the protocol you wish to use. Because the two supported protocols work differently, the operations you can perform depend on which protocol you are using. For example, the GetHeader method only works with HTTP (HTML documents).
However, there are a few procedures that are common to both protocols. Basically, in order to use either protocol, you must:
Set the AccessType property to a valid proxy server.
Invoke the OpenURL method with a valid URL.
Invoke the Execute method with a valid URL and command appropriate to the protocol.
Use the GetChunk method to retrieve data from the buffer.
Setting the AccessType Property: Using a Proxy Server
In order to make any kind of connection to the Internet, you must determine how your computer is connected to the Internet. If you are on an intranet, you will probably be connected to the Internet via a proxy server.
In short, a proxy server is an intermediary between your computer and the Internet. All computers on an intranet that need to connect to the Internet must do so through a proxy server. Thus the proxy functions as a firewall between the intranet and the Internet, discarding invalid end-user and external requests, thereby protecting the intranet from hostile actions.
To find the proxy settings on your computer
Note The following steps apply only to Windows 95, Windows NT® 4.0, or later systems.
On the Taskbar of your computer, click Start.
On the Settings item, click the Control Panel.
Double-click the Internet icon.
On the Internet Properties dialog box, click Connection.
Under Proxy Server, confirm that the Connect Through a Proxy Server check box is selected.
If it is selected, click Settings. The name of proxy servers you use for various protocols will be found in the dialog box. If no proxy is defined, contact your system administrator for available proxy servers.
If you intend to use a proxy other than that named in the dialog box, set the AccessType property to icNamedProxy (2). Then set the Proxy property to the name of the proxy, as shown in the code below:
Inet1.Proxy = "myProxyName"
Inet1.AccessType = icNamedProxy
On the other hand, if you are content to use the default proxy (as determined by your computer's registry), ignore the Proxy property, and simply set the AccessType to icUseDefault (0).
The settings for AccessType are shown in the following table:
Constant Value Description
icUseDefault 0 (Default) Use Defaults. The control uses default settings found in the registry to access the Internet.
icDirect 1 Direct to Internet. The control has a direct connection to the Internet.
icNamedProxy 2 Named Proxy. Instructs the control to use the proxy server specified in the Proxy property.
Invoke the OpenURL Method
After you set the AccessType property, the most basic operation is to use the OpenURL method with a valid URL. When you use the OpenURL method, the result will depend on the target URL. For example, the following URL will return the HTML document found at www.microsoft.com:
' A TextBox control named Text1 contains the
' result of the method. The Internet Transfer
' control is named Inet1.
Text1.Text = Inet1.OpenURL("http://www.microsoft.com")
As a result, the TextBox control is filled with the HTML source, which may resemble the figure below:
In this case, the default action was to return the HTML document located at the URL. However, if the URL is modified to target a specific text file, the actual file would be retrieved. For example, the following code:
Text1.Text = Inet1. _
OpenURL("ftp://ftp.microsoft.com/disclaimer.txt")
would result in the actual text of the file, as shown below:
Tip When you use either the OpenURL or Execute method, you need not set the Protocol property. The Internet Transfer control will automatically set itself to the correct protocol, as determined by the protocol portion of the URL.
Finally, you can use the OpenURL method with a URL that includes appended data. For example, many Web sites offer the ability to search a database. To search, send a URL that includes the search criteria. For example, the following code would use a search engine named "search.exe" with the criteria "find=Maui."
Dim strURL As String
strURL = _
"http://www.megaphone43.com/cgi-bin/search.exe?find=maui
Text1.Text = Inet1.OpenURL(strURL)
If the search engine finds a match for the criteria, an HTML document would be assembled and returned with the appropriate information.
Saving to a File Using the OpenURL Method
If you wish to save the data retrieved through the OpenURL method to a file, use the Open, Put, and Close statements, as shown in the code below. This example streams a binary file into a Byte array before saving the data to disk:
Dim strURL As String
Dim bData() As Byte ' Data variable
Dim intFile As Integer ' FreeFile variable
strURL = _
"ftp://ftp.microsoft.com/Softlib/Softlib.exe"
intFile = FreeFile() ' Set intFile to an unused
' file.
' The result of the OpenURL method goes into the Byte
' array, and the Byte array is then saved to disk.
bData() = Inet1.OpenURL(strURL, icByteArray)
Open "C:\Temp\Softlib.exe" For Binary Access Write _
As #intFile
Put #intFile, , bData()
Close #intFile
A similar procedure can be used to write a text file to disk, except no Byte array is needed; the data is saved directly to the file:
Dim strURL As String ' URL string
Dim intFile As Integer ' FreeFile variable
IntFile = FreeFile()
strURL = "http://www.microsoft.com"
Open "c:\temp\MSsource.txt" For Output _
As #IntFile
Write #IntFile, Inet1.OpenURL(strURL)
Close #IntFile
Synchronous and Asynchronous Transmission
The OpenURL method results in a synchronous transmission of data. In this context, synchronous means that the transfer operation occurs before any other procedures are executed. Thus the data transfer must be completed before any other code can be executed.
On the other hand, the Execute method results in an asynchronous transmission. When the Execute method is invoked, the transfer operation occurs independently of other procedures. Thus, after invoking the Execute method, other code can execute while data is received in the background.
What does this mean for the user of the Internet Transfer control? In short, using the OpenURL method results in a direct stream of data that you can save to disk (as shown above), or view directly in a TextBox control (if the data was text). On the other hand, if you use the Execute method to retrieve data, you must monitor the control's connection state using the StateChanged event. When the appropriate state is reached, invoke the GetChunk method to retrieve data from the control's buffer. This operation is discussed in greater detail below.
Using the Execute Method with the FTP Protocol
The Execute method has four arguments: url, operation, data, and requestHeaders. FTP operations take only the operation argument and the url argument, which is optional. For example, to get a file from a remote computer, you could use the following code:
Inet1.Execute "FTP://ftp.microsoft.com", _
"GET disclaimer.txt C:\Temp\Disclaimer.txt"
If you are used to using FTP to retrieve files from anonymous FTP servers, you will be familiar with certain commands used to navigate through server trees, and to retrieve files to a local hard disk. For example, to change directory with the FTP protocol, you would use the command "CD" with the path of the directory you wish to change to.
For the most common operations, such as putting a file on a server and retrieving a file from a server, the Internet Transfer control uses the same or a similar command with the Execute method. For example, the following code uses the "CD" command as an argument of the Execute method to change directory:
' The txtURL textbox contains the path to open. The
' txtRemotePath textbox contains the path to change to.
Inet1.Execute txtURL.Text, "CD " & txtRemotePath.Text
Note When using the Execute method with FTP commands, the data and requestHeaders arguments are not used. Instead, all of the operations and their parameters are passed as a single string in the operation argument; parameters are separated by a space. In the descriptions below, do not confuse the terms "file1" and "file2" with the data and requestHeaders arguments.
The syntax for FTP operations is:
operationName file1 file2
For example, to get a file, the following code includes the operation name ("GET"), and the two file names required by the operation:
' Get the file named Disclaimer.txt and copy it to the
' location C:\Temp\Disclaimer.txt
Inet1.Execute, _
"GET Disclaimer.txt C:\Temp\Disclaimer.txt"
The following table lists the supported FTP commands of the control:
Operation Description Example
CD file1 Change Directory. Changes to the directory specified in file1. Execute , "CD docs\mydocs"
CDUP Change to Parent. Same as "CD .." Execute , "CDUP"
DELETE file1 Deletes the file specified in file1. Execute , "DELETE discard.txt"
DIR [ file1 ] Searches the directory specified in file1. If file1 isn't supplied, the current working directory is searched. Use the GetChunk method to return the data. Execute , "DIR /mydocs"
GET file1 file2 Retrieves the remote file specified in file1, and creates a new local file specified in file2. Execute , _
"GET getme.txt C:\gotme.txt"
MKDIR file1 Creates a directory as specified in file1. Success is dependent on user privileges on the remote host. Execute , "MKDIR /myDir"
PUT file1 file2 Copies a local file specified in file1 to the remote host specified in file2. Execute , _
"PUT C:\putme.txt /putme.txt"
PWD Print Working Directory. Returns the current directory name. Use the GetChunk method to return the data. Execute , "PWD"
QUIT Terminate current connection Execute , "QUIT"
RECV file1 file2 Same as GET. Execute , _
"RECV getme.txt C:\gotme.txt"
RENAME file1 file2 Renames a file. Success is dependent on user privileges on the remote host. Execute ,
"RENAME old.txt new.txt"
RMDIR file1 Remove directory. Success is dependent on user privileges on the remote host. Execute , "RMDIR oldDir"
SEND file1 Copies a file to the FTP site. (same as PUT.) Execute , _
"SEND C:\putme.txt /putme.txt"
SIZE file1 Returns the size of the file specified in file1. Execute "SIZE /largefile.txt"
Important If your proxy server is a CERN proxy server, direct FTP connections (using the Execute method) are disallowed. In that case, to get a file, use the OpenURL method with the Open, Put, and Close statements, as shown earlier in "Saving to a File Using the OpenURL Method." You can also use the OpenURL method to get a directory listing by invoking the method and specifying the target directory as the URL.
Using the Execute Method with the HTTP Protocol
The HTTP protocol allows client machines to request data from the server using the GET, HEAD, POST, and PUT commands. These operations are shown in the following table:
Operation Description Example
GET Retrieves the file named in url. Execute "http://www.microsoft.com" & _
"/default.htm", "GET"
HEAD Retrieves only the headers of the file named in the URL property. Execute , "HEAD"
POST Provides additional data to support a request to the remote host. Execute , "POST", strFormData
PUT Replaces data at the specified URL. Execute , "PUT", "replace.htm"
The Common Gateway Interface and the Execute Method
Many World Wide Web sites offer the ability to search a database. This is accomplished by using the HTTP protocol's ability to send queries using the Common Gateway Interface (CGI).
It is not in the scope of this topic to explain the CGI; however, if you are familiar with the CGI, you can use the Execute method to construct an application that simulates the behavior of World Wide Web sites. For example, the code below shows a typical CGI query string:
http://www.findThis2490.com/cgi-bin/fin ... d=Hangzhou
This same query could be sent using the Execute method as shown below:
Dim strURL As String, strFormData As String
strURL = "//www.findThis2490.com/cgi-bin/find.exe"
strFormData = "find=Hangzhou"
Inet1.Execute strURL, "POST", strFormData
If you are expecting a result back from a server (as in the example above), you must use the GetChunk method to retrieve the resulting HTML document.
Using the State Event with the GetChunk Method
When you are downloading data from a remote computer, an asynchronous connection will be made. For example, using the Execute method with the operation "GET", will cause the server to retrieve the requested file. When the entire file has been retrieved, the State argument will return icResponseCompleted (12). At that point, you can use the GetChunk method to retrieve the data from the buffer. This is shown in the example below:
Private Sub Inet1_StateChanged(ByVal State As Integer)
Dim vtData As Variant ' Data variable.
Select Case State
' ... Other cases not shown.
Case icResponseCompleted ' 12
' Open a file to write to.
Open txtOperation For Binary Access _
Write As #intFile
' Get the first chunk. NOTE: specify a Byte
' array (icByteArray) to retrieve a binary file.
vtData = Inet1.GetChunk(1024, icString)
Do While LenB(vtData) > 0
Put #intFile, , vtData
' Get next chunk.
vtData = Inet1.GetChunk(1024, icString)
Loop
Put #intFile, , vtData
Close #intFile
End Select
End Sub
Logging on to FTP Servers
FTP servers come in two flavors: public and private. Public servers, as suggested by the name, are open to anyone. Private servers, on the other hand, won't let you log on unless you are a bona fide user of the server. In either case, the FTP protocol demands that you supply a user name and a password. The two are used to authenticate a user and allow (or disallow) subsequent actions.
To log on to public servers the common practice is to log in as "anonymous," (UserName = "anonymous") and send your e-mail name as the password. However this process is simplified even further with the Internet Transfer control. By default, if you do not supply UserName and Password property values, the control sends "anonymous" as your UserName, and your e-mail name for the Password.
If you are logging on to a private server, simply set the UserName, Password, and URL properties as appropriate, and invoke the Execute method, as shown in the example below:
With Inet1
.URL = "ftp://ftp.someFTPSite1020.com"
.UserName = "John Smith"
.Password = "mAuI&9$6"
.Execute ,"DIR" ' Returns the directory.
.Execute ,"CLOSE" ' Close the connection.
End With
After you have invoked the Execute method, the FTP connection will remain open. You can then continue to use the Execute method to perform other FTP operations such as CD and GET. When you have completed the session, close the connection using the Execute method with the CLOSE operation. You can also close the connection automatically by changing the URL property, and invoking either the OpenURL or Execute method; such action will close the current FTP connection, and open the new URL.
--------------------------------------------------------------------------------
Send feedback to MSDN.Look here for MSDN Online resources.
MSDN Library April 2000 писал(а):Visual Basic Concepts
Using the Winsock Control
A WinSock control allows you to connect to a remote machine and exchange data using either the User Datagram Protocol (UDP) or the Transmission Control Protocol (TCP). Both protocols can be used to create client and server applications. Like the Timer control, the WinSock control doesn't have a visible interface at run time.
Possible Uses
Create a client application that collects user information before sending it to a central server.
Create a server application that functions as a central collection point for data from several users.
Create a "chat" application.
Selecting a Protocol
When using the WinSock control, the first consideration is whether to use the TCP or the UDP protocol. The major difference between the two lies in their connection state:
The TCP protocol control is a connection-based protocol, and is analogous to a telephone — the user must establish a connection before proceeding.
The UDP protocol is a connectionless protocol, and the transaction between two computers is like passing a note: a message is sent from one computer to another, but there is no explicit connection between the two. Additionally, the maximum data size of individual sends is determined by the network.
The nature of the application you are creating will generally determine which protocol you select. Here are a few questions that may help you select the appropriate protocol:
Will the application require acknowledgment from the server or client when data is sent or received? If so, the TCP protocol requires an explicit connection before sending or receiving data.
Will the data be extremely large (such as image or sound files)? Once a connection has been made, the TCP protocol maintains the connection and ensures the integrity of the data. This connection, however, uses more computing resources, making it more "expensive."
Will the data be sent intermittently, or in one session? For example, if you are creating an application that notifies specific computers when certain tasks have completed, the UDP protocol may be more appropriate. The UDP protocol is also more suited for sending small amounts of data.
Setting the Protocol
To set the protocol that your application will use: at design-time, on the Properties window, click Protocol and select either sckTCPProtocol, or sckUDPProtocol. You can also set the Protocol property in code, as shown below:
Winsock1.Protocol = sckTCPProtocol
Determining the Name of Your Computer
To connect to a remote computer, you must know either its IP address or its "friendly name." The IP address is a series of three digit numbers separated by periods (xxx.xxx.xxx.xxx). In general, it's much easier to remember the friendly name of a computer.
To find your computer's name
On the Taskbar of your computer, click Start.
On the Settings item, click the Control Panel.
Double-click the Network icon.
Click the Identification tab.
The name of your computer will be found in the Computer name box.
Once you have found your computer's name, it can be used as a value for the RemoteHost property.
TCP Connection Basics
When creating an application that uses the TCP protocol, you must first decide if your application will be a server or a client. Creating a server means that your application will "listen," on a designated port. When the client makes a connection request, the server can then accept the request and thereby complete the connection. Once the connection is complete, the client and server can freely communicate with each other.
The following steps create a rudimentary server:
To create a TCP server
Create a new Standard EXE project.
Change the name of the default form to frmServer.
Change the caption of the form to "TCP Server."
Draw a Winsock control on the form and change its name to tcpServer.
Add two TextBox controls to the form. Name the first txtSendData, and the second txtOutput.
Add the code below to the form.
Private Sub Form_Load()
' Set the LocalPort property to an integer.
' Then invoke the Listen method.
tcpServer.LocalPort = 1001
tcpServer.Listen
frmClient.Show ' Show the client form.
End Sub
Private Sub tcpServer_ConnectionRequest _
(ByVal requestID As Long)
' Check if the control's State is closed. If not,
' close the connection before accepting the new
' connection.
If tcpServer.State <> sckClosed Then _
tcpServer.Close
' Accept the request with the requestID
' parameter.
tcpServer.Accept requestID
End Sub
Private Sub txtSendData_Change()
' The TextBox control named txtSendData
' contains the data to be sent. Whenever the user
' types into the textbox, the string is sent
' using the SendData method.
tcpServer.SendData txtSendData.Text
End Sub
Private Sub tcpServer_DataArrival _
(ByVal bytesTotal As Long)
' Declare a variable for the incoming data.
' Invoke the GetData method and set the Text
' property of a TextBox named txtOutput to
' the data.
Dim strData As String
tcpServer.GetData strData
txtOutput.Text = strData
End Sub
The procedures above create a simple server application. However, to complete the scenario, you must also create a client application.
To create a TCP client
Add a new form to the project, and name it frmClient.
Change the caption of the form to TCP Client.
Add a Winsock control to the form and name it tcpClient.
Add two TextBox controls to frmClient. Name the first txtSend, and the second txtOutput.
Draw a CommandButton control on the form and name it cmdConnect.
Change the caption of the CommandButton control to Connect.
Add the code below to the form.
Important Be sure to change the value of the RemoteHost property to the friendly name of your computer.
Private Sub Form_Load()
' The name of the Winsock control is tcpClient.
' Note: to specify a remote host, you can use
' either the IP address (ex: "121.111.1.1") or
' the computer's "friendly" name, as shown here.
tcpClient.RemoteHost = "RemoteComputerName"
tcpClient.RemotePort = 1001
End Sub
Private Sub cmdConnect_Click()
' Invoke the Connect method to initiate a
' connection.
tcpClient.Connect
End Sub
Private Sub txtSendData_Change()
tcpClient.SendData txtSend.Text
End Sub
Private Sub tcpClient_DataArrival _
(ByVal bytesTotal As Long)
Dim strData As String
tcpClient.GetData strData
txtOutput.Text = strData
End Sub
The code above creates a simple client-server application. To try the two together, run the project, and click Connect. Then type text into the txtSendData TextBox on either form, and the same text will appear in the txtOutput TextBox on the other form.
Accepting More than One Connection Request
The basic server outlined above accepts only one connection request. However, it is possible to accept several connection requests using the same control by creating a control array. In that case, you do not need to close the connection, but simply create a new instance of the control (by setting its Index property), and invoking the Accept method on the new instance.
The code below assumes there is a Winsock control on a form named sckServer, and that its Index property has been set to 0; thus the control is part of a control array. In the Declarations section, a module-level variable intMax is declared. In the form's Load event, intMax is set to 0, and the LocalPort property for the first control in the array is set to 1001. Then the Listen method is invoked on the control, making it the "listening control. As each connection request arrives, the code tests to see if the Index is 0 (the value of the "listening" control). If so, the listening control increments intMax, and uses that number to create a new control instance. The new control instance is then used to accept the connection request.
Private intMax As Long
Private Sub Form_Load()
intMax = 0
sckServer(0).LocalPort = 1001
sckServer(0).Listen
End Sub
Private Sub sckServer_ConnectionRequest _
(Index As Integer, ByVal requestID As Long)
If Index = 0 Then
intMax = intMax + 1
Load sckServer(intMax)
sckServer(intMax).LocalPort = 0
sckServer(intMax).Accept requestID
Load txtData(intMax)
End If
End Sub
UDP Basics
Creating a UDP application is even simpler than creating a TCP application because the UDP protocol doesn't require an explicit connection. In the TCP application above, one Winsock control must explicitly be set to "listen," while the other must initiate a connection with the Connect method.
In contrast, the UDP protocol doesn't require an explicit connection. To send data between two controls, three steps must be completed (on both sides of the connection):
Set the RemoteHost property to the name of the other computer.
Set the RemotePort property to the LocalPort property of the second control.
Invoke the Bind method specifying the LocalPort to be used. (This method is discussed in greater detail below.)
Because both computers can be considered "equal" in the relationship, it could be called a peer-to-peer application. To demonstrate this, the code below creates a "chat" application that allows two people to "talk" in real time to each other:
To create a UDP Peer
Create a new Standard EXE project.
Change the name of the default form to frmPeerA.
Change the caption of the form to "Peer A."
Draw a Winsock control on the form and name it udpPeerA.
On the Properties page, click Protocol and change the protocol to UDPProtocol.
Add two TextBox controls to the form. Name the first txtSend, and the second txtOutput.
Add the code below to the form.
Private Sub Form_Load()
' The control's name is udpPeerA
With udpPeerA
' IMPORTANT: be sure to change the RemoteHost
' value to the name of your computer.
.RemoteHost= "PeerB"
.RemotePort = 1001 ' Port to connect to.
.Bind 1002 ' Bind to the local port.
End With
frmPeerB.Show ' Show the second form.
End Sub
Private Sub txtSend_Change()
' Send text as soon as it's typed.
udpPeerA.SendData txtSend.Text
End Sub
Private Sub udpPeerA_DataArrival _
(ByVal bytesTotal As Long)
Dim strData As String
udpPeerA.GetData strData
txtOutput.Text = strData
End Sub
To create a second UDP Peer
Add a standard form to the project.
Change the name of the form to frmPeerB.
Change the caption of the form to "Peer B."
Draw a Winsock control on the form and name it udpPeerB.
On the Properties page, click Protocol and change the protocol to UDPProtocol.
Add two TextBox controls to the form. Name the TextBox txtSend, and the second txtOutput.
Add the code below to the form.
Private Sub Form_Load()
' The control's name is udpPeerB.
With udpPeerB
' IMPORTANT: be sure to change the RemoteHost
' value to the name of your computer.
.RemoteHost= "PeerA"
.RemotePort = 1002 ' Port to connect to.
.Bind 1001 ' Bind to the local port.
End With
End Sub
Private Sub txtSend_Change()
' Send text as soon as it's typed.
udpPeerB.SendData txtSend.Text
End Sub
Private Sub udpPeerB_DataArrival _
(ByVal bytesTotal As Long)
Dim strData As String
udpPeerB.GetData strData
txtOutput.Text = strData
End Sub
To try the example, press F5 to run the project, and type into the txtSend TextBox on either form. The text you type will appear in the txtOutput TextBox on the other form.
About the Bind Method
As shown in the code above, you must invoke the Bind method when creating a UDP application. The Bind method "reserves" a local port for use by the control. For example, when you bind the control to port number 1001, no other application can use that port to "listen" on. This may come in useful if you wish to prevent another application from using that port.
The Bind method also features an optional second argument. If there is more than one network adapter present on the machine, the LocalIP argument allows you to specify which adapter to use. If you omit the argument, the control uses the first network adapter listed in the Network control panel dialog box of the computer's Control Panel Settings.
When using the UDP protocol, you can freely switch the RemoteHost and RemotePort properties while remaining bound to the same LocalPort. However, with the TCP protocol, you must close the connection before changing the RemoteHost and RemotePort properties.
--------------------------------------------------------------------------------
Send feedback to MSDN.Look here for MSDN Online resources.
LexBondAgent007 писал(а):FAKK2
А искал я через Yandex - лучше и быстрее думаю не получиться - тут и ссылок никаких не надо.
Сейчас этот форум просматривают: AhrefsBot, SemrushBot и гости: 154