Introduction to WinSock
Socket was originally developed by the University of California, Berkeley, as the network communication interface of UNIX operating system. With the widespread use of UNIX, Socket has become one of the most popular network communication application interfaces. In the early 1990s, several companies, such as Sun Microsystems, JSB, FTP Software, Microdyne and Microsoft, jointly customized a set of standards, that is, Windows Socket specification, or WinSock for short.
There are two main ways to write network programs with VB: 1.winsock control 2.winsockAPI.
Second, the use of WinSock controls
The main properties of 1. WinSock control
A. protocol attributes
The Protocol property allows you to set the protocol that WinSock controls use to connect to a remote computer. Optional protocol is VB, and the constants of TCP and UDP are sckTCPProtocol and sckUDPProtocol respectively. The default protocol of Winsock control is TCP. Note: Although the protocol can be set at runtime, it must be set after the connection is not established or disconnected.
B.SocketHandle property
SocketHandle returns the handle of the current socket connection, which is a read-only property.
C.RemoteHostIP property
The RemoteHostIP property returns the IP address of the remote computer. On the client side, when using the Connect method of the control, the IP address of the remote computer is assigned to the RemoteHostIP property, while on the server side, after the ConnectRequest event, the IP address of the remote computer (client) is assigned to the property. If the UDP protocol is used, after the DataArrival event, the IP of the computer that sent the UDP message will be assigned to this property.
D.ByteReceived property
Returns the number of bytes in the current receive buffer.
E. State property
Returns the current state of the WinSock control
Constant value description
SckClosed 0 default value, off.
SckOpen 1 is already open.
Listening 2
SckConnectionPending 3 connection has been suspended.
SckResolvingHost 4 identifies the host.
SckHostResolved 5 has recognized the host.
SckConnecting 6 is connecting.
SckConnected 7 is connected.
SCK CLOSING Eight peers are closing the connection.
SckError 9 error
2.WinSock main methods
A. Binding method
Using the Bind method, you can fix a port number for the control so that other applications can no longer use it.
B. Listening methods
The Listen method is only useful when using the TCP protocol. It puts the application in a listening detection state.
C. Connection method
When a local computer wants to establish a connection with a remote computer, it can call the connect method.
The specification of the Connect method call is:
Connecting a remote host, a remote port
D. Acceptance method
When the server receives the client's connection request, the server has the right to decide whether to accept the client's request.
E.SendData method
After the connection is established, to SendData, you can call the senddata method, which has only one parameter, that is, the data to be sent.
F.GetData method
When a local computer receives data from a remote computer, the data is stored in a buffer. To GetData from the buffer, you can use the getdata method. The GetData method call specification is as follows:
GetData data, [type, ][maxLen]
It gets the data with the longest maxLen length from the buffer and stores it as type in data. After obtaining the data, it empties the corresponding buffer.
G.PeekData method
Similar to the GetData method, but PeekData does not empty the buffer after getting the data.
3.Winsock control main event
A.ConnectRequest event
When the local computer receives a connection request sent by a remote computer, the ConnectRequest event of the control will be triggered.
B.SendProgress event
When a computer at one end sends data to a computer at the other end, the SendProgress event will be triggered. The SendProgress event records the number of bytes sent and the number of bytes remaining in the current state.
C. sending the completion event
Triggered when all data transfer is completed.
D. Data arrival event
This event will be triggered when new data is received after the connection is established. Note: If the buffer is not empty before new data is received, this event will not be triggered.
E. Error events
Any error in the work will trigger this event.
See the attachment for examples.
Third, the use of WinSockAPI.
1.WSAStartup function
In order to call any Winsock API function in your application, the first thing you need to do is to initialize Winsock service through WSAStartup function, so you need to call WSAStartup function.
Declare the function WSA Startup Lib "WS2 _ 32.dll" _
(ByVal wversionlong,lpWSAData As WSAData)Long
This function has two parameters: wVersionRequired and lpWSAData. The wVersionRequired parameter defines the highest version that Windows sockets can provide. Its upper byte defines the minor version number, and the lower byte defines the major version number. The following are two examples of Winsock versions used in VB:
Initialization version 1. 1.
lngRetVal = wsa startup(& amp; H 10 1,udtWinsockData)
Initialize version 2.2
lngRetVal = wsa startup(& amp; H202,udtWinsockData)
The second parameter is the data structure of WSADATA, which receives data when executing Windows Sockets.
Sign WSAData
WVersion in integer form
WHighVersion in integer form
SZ description As String * wsa description _ LEN
szSystemStatus As String * wsa sys _ STATUS _ LEN
IMaxSockets in integer form
IMaxUdpDg is an integer
LpVendorInfo is Long.
End type
The following table describes the data members:
Field description
Windows socket version information.
WHighVersion is the highest version that supports Winsock by loading library files.
It is usually the same as the wVersion value.
SZ describes the detailed description of Windows sockets at execution time.
SzSystemStatus contains related status and configuration information.
IMaxSockets indicates the maximum number of sockets open at the same time, and 0 indicates no limit.
IMaxUdpDg means the maximum number of datagrams that can be opened at the same time, and 0 means there is no limit.
Information retention specified by LpVendorInfo supplier
There is no return value of lpVendorInfo in Winsock version 1. 1 and 2.2. Because winsock 2 supports multiple transmission protocols, iMaxSockets and iMaxUdpDg can only be used in winsock 1. 1 which only supports TCP/TP. To get these values in Winsock 2, you can use the WSAEnumProtocols function.
If it succeeds or returns an error code, the function returns 0.
Error code meaning
WSASYSNOTREADY pointed out that the network is not ready for transmission.
WSAVERNOTSUPPORTED The current WinSock implementation does not support the Windows Socket specification version specified by the application.
WSAEINPROGRESS is blocking WinSock calls.
The protocol requested by WSAEPROCLIM is not configured in the system, or its implementation is not supported.
Wsaedefault lpwsadata is not a valid pointer.
2.WSACleanup function
Every time you call WSAStartup function, you need to call WSACleanup function to inform the system to unload the library file and empty the allocated resources. This function is very simple, with no parameters:
Declare the function wsacleanuplib "ws2 _ 32.dll" () as Long.
3. Establish socket function
Declare the function socket library "ws2 _ 32.dll" (byval af as long, _
ByVal s_type is Long,
ByVal protocol is as long)
This function has three parameters that define what kind of socket to create. These three parameters are:
Parameter describes enumeration type.
Af address series specification. Address family
S _ s_typeThe type specification of the new socket. SocketType
Protocol used for socket socket protocol.
It is specific to the indicated address.
Family.
Address series:
AF_UNSPEC = 0 '/* Not specified */
AF_UNIX = 1 '/* Host local (pipeline, portal) */
AF_INET = 2 '/* Internet: UDP, TCP, etc. */
Af _ implicit = 3'/* ARPANET IMP address */
AF_PUP = 4 '/* pup protocol: for example, BSP */
AF_CHAOS = 5 '/* mit chaos protocol */
AF_NS = 6 '/* XEROX NS protocol */
AF_IPX = AF_NS '/* IPX protocols: IPX, SPX, etc. */
AF_ISO = 7 '/* ISO protocol */
AF_OSI = AF_ISO '/* OSI is ISO */
AF_ECMA = 8 '/* European computer manufacturers */
AF_DATAKIT = 9 '/* datakit protocol */
AF_CCITT = 10 '/* CCITT protocol, X.25, etc. */
AF _ SNA = 1 1 '/* IBM SNA */
AF_DECnet = 12 '/* DECnet */
AF_DLI = 13 '/* direct data link interface */
AF_LAT = 14 '/* LAT */
AF _ hy link = 15 '/* NSC Hyperchannel */
AF _ apple talk = 16 '/* apple talk */
AF_NETBIOS = 17 '/* NetBios style address */
AF _ voice view = 18 '/* voice view */
AF_FIREFOX = 19 '/* Protocol from FIREFOX */
AF_UNKNOWN 1 = 20 '/* Someone is using this! */
AF_BAN = 2 1 '/* Banyan */
AF_ATM = 22 '/* local ATM service */
AF_INET6 = 23 '/* Internet version 6 */
AF _ CLUSTER = 24 '/* Microsoft wolf pack */
AF _ 12844 = 25 '/* IEEE 1284.4 WG AF */
AF_MAX = 26
Socket type:
SOCK_STREAM = 1' /* stream socket */
SOCK_DGRAM = 2' /* datagram socket */
SOCK _ RAW = 3 '/* RAW- protocol interface */
SOCK_RDM = 4' /* Reliable delivered message */
SOCK_SEQPACKET = 5' /* Ordered packet flow */
Agreement:
IPPROTO_IP = 0 '/* Virtual IP */
IPPROTO_ICMP = 1 '/* control message protocol */
IPPROTO_IGMP = 2 '/* Internet Group Management Protocol */
Ipproto _ GGP = 3'/* Gateway 2 (deprecated) */
IPPROTO_TCP = 6 '/* tcp */
IPPROTO_PUP = 12 '/* pup */
IPPROTO_UDP = 17 '/* User Datagram Protocol */
IPPROTO_IDP = 22 '/* xns idp */
IPPROTO_ND = 77 '/* unofficial network disk proto */
IPPROTO_RAW = 255 '/* Original IP packet */
IPPROTO_MAX = 256
This function can establish a network socket using a specific protocol. For example, for UDP protocol, it can be written as follows:
S = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP)
S = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)
4. Turn off the socket function
Declare the function closesocket lib "ws2 _ 32.dll" (byvals as Long) as long.
When the socket is created, the function has a Handle parameter.
5. Connection function
Declare the function connection library "ws2 _ 32.dll" (byvals as long, _
ByRef name is sockaddr_in, _
As long as, as long as
parameter
Socket handle for s connection.
Name the address where the connection is established.
The length of the namelen connection address.
Return value
Returns 0 on success. Otherwise, it returns SOCKET_ERROR and the corresponding error number err. lastteller error.
Obviously, when calling this function, we need to know the socket handle, port number and host name (or host IP address) of the computer to be connected. We know that the Connect method of Winsock control depends on two variables: RemoteHost and RemotePort. This method does not need a socket handle because it is already encapsulated in a COM object. You might think that the connect function should also accept the same variable settings, however, this is not the case. The transmission of the host address and port number of the connect function depends on the sockaddr_in structure.
Public type sockaddr_in
Sin_family is an integer
Sin_port is an integer
As long as sin_addr.
Sin_zero( 1 to 8) as bytes.
End type
6. Socket helper function
Declare the function binding library "ws2 _ 32.dll" (byvals as long, _
ByRef name is sockaddr_in, _
ByRef namelen is the same length.
S is a Socket created by using the socket function, name is a pointer to the structure describing the communication object, and namelen is the length of the structure. knot
Components in this structure include:
IP address: corresponding to name.sin _ addr.s _ addr
Port number: corresponding to name.sin_port.
Port numbers are used to represent different processes (i.e. applications) on the same computer, and there are two ways to assign them:
The first allocation method is that the process allows the system to automatically allocate a port number for the socket, and only needs to specify the port number as 0 before calling bind. The port number automatically assigned by the system is between 1024 and 5000, and any TCP or UDP port between 1 and 1023 is reserved. The system does not allow any process to use the reserved port unless its valid user ID is zero (that is, superuser).
The second allocation method is that the process specifies a specific port for the socket. This is very useful for servers that need to allocate a well-known port for sockets. The specified range is between 1024 and 65536.
Address type: corresponding to name.sin_family, generally assigned as AF_INET, indicating an Internet address (i.e. IP address). IP address is usually represented by dot, but it is actually a long integer of 32 bits, which can be converted by inet_addr () function.
7. Socket listener function
Declare the function listenlib "ws2 _ 32.dll" (byvals is Long, ByVal backlog is Long) as Long.
The listen function is used to set the socket to listening state, which means that the socket is ready to connect. Note that this function is generally used in service programs, where s is a Socket created by using the socket function, and the backlog parameter is used to set the number of clients waiting to connect.
8. Accept the connection request
Declare the function acceptlib "ws2 _ 32.dll" (byvals is Long, ByRef addr is sockaddr_in, _
Byrefaddlen is as long)
The server application calls this function to accept the connection request of the client socket. The return value of the accept () function is a new socket, which can be used to send and receive information between the server and the client, while the original socket can still accept the connection request of other users.
9. Receiving information
Declare the function recvlib "ws2 _ 32.dll" (byvals as long, _
ByRef buf As Any,_
ByVal buflen as long, _
ByVal logo is the same length)
S is the identifier of the connected socket.
Buffer data received by buf
Lens buffer length
Flags specifies the identity to call from.
The first parameter is the handle of the socket-the return value of the socket function. In other words, we need to tell the recv function which socket is accessing the function.
The second parameter is: a buffer where some data can be loaded after the function is executed. But it doesn't have to be long enough to receive all the data in the Winsock buffer, and the size of the buffer is limited to 8 192 bytes (8 kilobytes). Therefore, if the data size in Winsock buffer is larger than the buffer of recv function, the function must be called several times until all the data are obtained.
If the application defines the length of the buffer, the recv function must know how many bytes the buffer can hold. The third parameter is for this purpose.
The last parameter is optional and we won't use it today. This parameter has two selection flags: MSG_PEEK and MSG_OOB, which are used to change the behavior of the function.
MSG_PEEK gets data from input data. Data is copied to the buffer, but it is not deleted from the input queue. Function returns the number of bytes currently ready to receive.
MSG_OOB processes OOB (out of band) data. There are two types of packets on the network, ordinary packets and out-of-band packets. Out-of-band outsourcing can be determined by checking the specific flag of TCP/IP header.
10. Send information
Declare the function sendlib "ws2 _ 32.dll" (byvals as long, _
ByRef buf As Any,_
ByVal buflen as long, _
ByVal logo is the same length)
Please refer to the parameter information received.
Fourthly, the server interacts with the client.
At present, the most commonly used method is that the service program listens to the service request at a well-known address (including port information), that is, the service process has been dormant until a customer sends a connection request to this service address. At this time, the service program is awakened and responds to the customer's request appropriately. Note that the interaction between the server and the client can be connection-oriented (based on streaming sockets) or connectionless (based on datagram sockets).
Computer network server
Socket ()
|
Binding ()
|
Listen () client
|
| Socket ()
| establish contact |
accept()& lt; -Connect ()
| Request data |
recv()& lt; -Send ()
| |
Handling service requests |
| Response data |
send()-& gt; Receive ()
| |
Close () Close ()
Verb (short for verb) others
Comparison: WinSock controls
Advantages: simple use and small workload.
Disadvantages: Few functions only support TCP and UDP protocols, and WinSock controls are needed (there is no MSWINSCK installed in the system. The default is OCX file).
Suitable for beginners
Wensuokapi
Advantages: powerful function, support for multiple protocols and flexible use. Wsock32.dll(28k) or ws2_32.dll(69K) called by WinSockAPI comes with Windows system function library, so don't worry about insufficient files.
Disadvantages: complex use, large amount of programming, and need a certain foundation.
Suitable for demanding network programs.
/tech/program/22649.html