Winsock programming in VB
One. introduction
Socket is intended to "socket", which represents a point-to-point information transmission. Early communication programming specification on UNIX systems, communication between two sides consists of two "servers" and "customers", based on IP protocol, based on TCP or UDP specifications. Establishing the process of establishing communication, even a "socket" is established, and the "socket" is established, and the "socket" is established to communicate various information. With the popularity of the Windows system, some people start to transplant on the Windows platform based on the original basis. Microsoft wrote early (Message Drivers, etc.) "Sockets" programming API, which is generally prepared early in the early stage, generally called "Winsock API". After Microsoft's ActiveX technology, Microsoft provides a ActiveX control called "Winsock", which is convenient for programmers who use VB programmers to "socket" programming, so that we don't have to go deep into socket details. Communication.
Below, let's contact this control first.
two. WinSocket control details
This control is not visible when the user is running, providing a simple way to access TCP and UDP network services without having to understand the underlying detail, you only need to set the property, call it in the appropriate time.
The main properties are:
BYTESRECEIVED: Returns the number of bytes in the current buffer, we can use the getData method to receive data. Read-only and not designed
Localhostname: Returns the native name string, not available when designing.
Localip: Returns the IP address string expressed in the format (xxx.xxx.xxx.xxx) format. Not available when design, read only when running.
LocalPort: The address used by this machine, readable, design, long-type. For customers, if you do not need to specify a port, send data with port 0. In this case, the control will randomly select a port. After a connection is determined, the port of TCP. For the server, refers to the port used to listen. If set to 0, use the random number. After calling the Listen method, the property automatically contains the port used. Port 0 is always used to establish dynamic connections between two computers. Customers want to get a random port through port 0 to connect to the server with a "callback".
Protocol: Socket type, one of the two of TCP or UDP, default is TCP type. Set to SCKTCPPROTOCOL indicate that the TCP protocol SCKUDPPROTOCOL represents the UDP protocol. Use the Close method to close before this property is reset.
Remotehost: Hosts send or receive data, you can provide hostnames such as "ftp://ftp.microsoft.com" or an IP address string, such as "100.0.1.1".
Remotehostip: IP address of the remote host. For the client program, use the Connect method after the connection is determined, this property contains the IP name string of the remote host. For server programs, this property contains an IP string after introducing connection requirements (ConnectionRequest event). When using UDP sockets, this property is a machine IP address string that sends UDP data after the DataArrival event occurs.
RemotePort: Connect the socket port value. For example, the HTTP application usually uses an 80-port, and FTP uses 21.
State: The status of the control is read-only and is not available. Can be the following value:
Constant description
SCKCLOSED 0 Default, turn off socket
Sckopen 1 opens the socket
Scklistening 2 is listening to the port
Sckconnectionpending 3 is undergoing undetermined connections
SckresolvingHost 4 Positive Analysis Host Address SCKHOSTRESOLVED 5 Host address has been parsed
SckConnecting 6 is connected
SckConnected 7 is connected
SCKClosing 8 connection is closed
Sckerror 9 error
Other properties are similar to general controls.
The main methods are:
Accept: For TCP server applications only. This method is used to respond to ConnectionRequest events when introducing a connection. Syntax: Object.Accept requestid Return Value: Void. The REQUESTID parameter must be passed to this method to generate a new Socket instance for actual information transmission.
Bind: Set LocalPort and localip for TCP connections. Use when you have multiple protocol adapters. Syntax: Object.bind LocalPort, localip. LocalPort This port is used to connect, localip generates a connection IP address. If the relevant properties have been set, you don't have to carry the relevant parameters. This method is called before calling the Lisent method.
Close: Turn off the TCP connection in the customer or server. Grammar: Object.close. Parameters: None. Return value: void.
GetData: Receives data blocks stored in variable types. Return value: void. Syntax: Object.getdata Data, [Type,] [Maxlen]. Data: The variable of the data is received, if the space is not enough, set it to empty. Type: Optional, received type, it is set. Maxlen: Optional parameters. Set the size of the receiving array or string type data. If the parameter is the shortage, all data will be received. This parameter is ignored if the data type outside the array or string is provided. TYPE can be set to a common data type. This method is usually used in the DataArrival event. This event contains TOTALBYTES parameters. If you set Maxlen less than TotalBytes parameters, you will get a warning message that will be lost by the remaining bytes represented by 10040.
Listen: Create a socket set to the listening mode. This method is only used for TCP connections. Object.listen
Parameters: None. Return value: void. After tapping Listen, a ConnectionRequest event occurs when a connection is introduced. When processed ConnectionRequest, the application must use an Accpet method to respond.
Peekdata: Similar to getData but Peekdata does not remove data from the input queue. This method is only used for TCP connections. Grammar: Object.peekData Data, [Type,] [Maxlen]
Senddata: Send a host from the remote host. Return value: void. Grammar: Object.senddata Data. DATA: The data to be sent, use byte arrays. When the Unicode format is used, it will be converted to an ANSI string before sending.
The events occurring:
Close: The remote host occurs. The Close method should be used for the correct TCP connection.
Connect: When the connection action is completed. Grammar: Object.connect (). This event indicates successful connection.
ConnectionRequest: When a remote host is required to determine a connection. Used only for TCP server applications. RemoteHostip and RemotePort properties store information about the client after this event. Syntax: Object_ConnectionRequest (Requestid As Long). RequestID: The request ID of the introduced connection. This parameter passes the second control instance in the Accept method. The server can decide whether to deny that it can be connected. If the introduced connection is not recognized, the customer will be subject to a CLOSE event. Use the Accept method to accept the introduced connection. DataArrival: occurs when new data arrives. Grammar: Object_dataArrival (bytestotal as long). Bytestotal, long. The amount of data received. This event will not happen again before you call the getData method. Active only when there is a new data arrive. You can check how much data is valid at any time to check how much data is checked.
Error: Indicates that an error has occurred. Limited to the space, the error code is ignored.
SendComplete: When the send action is completed. Syntax: Object_sendComplete. Parameters: None.
SendProgress: This event is generated when sending data. Grammar: Object_sendProgress (bytessent as long, bytesremaining as long). BYTESSENT: The amount of data sent since the event. BYTESREMAINING: The data that is waiting for transmission in the buffer.
three. Winsocket programming application example
It can be seen that the Winsocket control allows us to communicate with two transport protocols. The TCP protocol allows you to establish and maintain a connection with the distal host, and transmit data in a "stream" by connection. Customers who use this method must know the name of the server (RemoteHost property), but also know that the server is listen, and then call the Connect method. The server program must set the listening port (LocalPort) of this Scoket, then call the listen method; when the customer requests a connection, the server generates the ConnectionRequest event. If the server wants to complete the connection, call the Accept method to be approved. Once the connection is established, both computers can be sent using the SendData method. When data is received, a DataArrival event occurs, and we can call the getData method to receive data in this event. And if the UDP protocol is used, the client sets the local listener port (LocalPort property), the server computer sets the client's name (Remotehost) and listening port properties (Remoteport), then call the SendData method to send data; client in DataArrival event Use the getData method to receive information.
To demonstrate programming details, you can write a "Chat" application for two people: program parties to clients and servers. Start the server application first, then start the customer program, establish a connection after the handshake, and then communicate with each other, and because the TCP protocol can be used to real-time and accurate transmission of information.
Specific steps are as follows:
Server program preparation:
Establish standard projects, then select Components under Project ..., select Microsoft Winsock Control 5.0 from the pop-up dialog box, and then make a control panel in the control panel will be added to Winscok. This control is "main foot" in this article. Change the CAPTION attribute of Form1 to "Socksrv" and add the Winsock control just join the project on the form. Add three Label and TextBox controls, a Command control, setting their properties and findings: label1.caption = "Listening port:", label2. Caption = "Customer Message:", Label3. CAPTION = "server message:" TextBox1.text = "900", this control is used to set the Winsock server-side listener port.
TextBox2.text = "", TextBox2. Multilin = Ture, TextBox2.scrollbar = 2. The control allows the initial information to be blank by setting the text attribute, and the multilin property can allow multi-line display to display the communication between the server in real time. Set the scrollbar attribute 2, you can join a vertical roller, allowing multiple line information to be displayed. The main role of this control is the exchange of communication between the server and the customer real-time display.
The properties of the TextBox3 are set to TextBox2, the main role is to enter the information of the server user.
The title of Command1 is "listening" to connect the server to the connection request state of the listening port.
Add code, the specific content can be set as follows: In the Form1.Load event Add: Winsock1.localport = Text1.text, the function is to set the listening port defined by Text1 to the Winsock control.
Add: in the CLICK event of Command1:
IF Winsock1.State <> SCKCLOSED THEN WINSOCK1.CLOSE 'Close it when the current socket is not closed
Winsock1.bind 'takes the value to take effect
Winsock1.Listen 'Listening Port Connection Request
Add code to several events in Winscok:
Private sub winsock1_connectionRequest (ByVal Requestid As Long)
IF Winsock1.State <> SCKCLOSED THEN WINSOCK1.CLOSE
Winsock1.Accept requestID 'When the connection request occurs when the number of ports occurs, immediately call the Accept method.
'Recognize the connection to take effect.
End Sub
Private sub winsock1_dataarrival (byval bytestotal as long)
DIM STRDATA AS STRING
Winsock1.Getdata strdata, vbstring 'When there is data arrival, call the getData method to receive it.
TEXT2.TEXT = STRDATA 'Update the received content in Text2
End Sub
The above is set to set the server-side settings, let's take a look at the client's program.
Establish a new standard engineering, add the Winsock control to the control panel according to the above method. Modify the project name "SCKCLIENT" and add Winsock control to the form. Add three Label and Text controls, two Command controls, their properties are: label1.caption = "server address:", Label2.caption = "information sent", label3.caption = "Customer Message". TEXT1.TEXT = "www.ysh.com", this is the server address or name that the customer wants to communicate with it, which should fill in the name of the server in the actual runtime or the IP address of the TCP / IP protocol. Www.ysh.com is my host name on the local area I am.
TEXT2.MULTILIN = TRUE, which is to be able to display the information sent by the server. In order to view all the information sent by the server, the ScollBar property should be set to 3.
Text3 should also be a control that allows multi-line display.
Caption of Command1 and Comand2 is "Connect", "Disconnected", which is used to determine the connection status of Winsock.
Add a corresponding code: Enter: Winsock1.RemotEport = "900" in Form_Load (), used to determine the port with the server to establish a socket.
Enter: in Command1_Click ():
If Winsock1.State <> SCKCLOSED THEN WINSOCK1.CLOSE 'If the socket is not closed, first close
Winsock1.remotehost = text1.text 'Determines the host name of the server
Winsock1.bind 'binding socket properties
Winsock1.connect 'issues a connection request to the server
Command1.enabled = false 'makes CommAND1 are not available
Command2.enabled = true 'now can disconnect it
Enter code in Command2_Click ():
Command1.enabled = TRUE
Command2.enabled = false
Winsock1.close 'Close the current socket
For each event of the Winsock control, you can refer to the following code:
Private sub winsock1_dataarrival (byval bytestotal as long)
Dim Str As String
Winsock1.getdata str, vbstring 'receive information according to string type
TEXT2.TEXT = STR 'Updated to Text2
End Sub
PRIVATE SUB WINSOCK1_CONNECT () 'pops up after the connection is successful
Msgbox "Connected to Server!"
End Sub
In order to reflect the contents of Text3 in real time to the server's information box, you need text3_change () to enter the following code:
IF Winsock1.State = Sckconnected Ten Winsock1.senddata Text3.Text
Writing, servers, and customers through the above settings, we can communicate on the network. Start the server, press the "Connection" button, wait for the client's request, then start the customer, enter the correct server address or host name, press the "Connection" button, indicate the connection success, at this time Whether you enter any information in the server or the customer's text3, you will display in real time in the TEXT2 of the other party, so a simple "chat" program starts working properly. four. Program description
Commissioning the above procedures requires certain skills. Because the Winsock control is based on the network-based control, the network must be completely installed on the machine, and the TCP / IP protocol is installed; at the same time, because of the C / S mode, it is necessary to run two processes simultaneously or The two have been running on a machine that has been networked through the TC / IP protocol. On standing machine requires certain skills, we can start two VBs at the same time, open two projects of customers and servers, and start them through the task to switch. This can utilize the multitasking of Windows 95 to complete the network simulation on a single machine.
This program is just a simple demonstration of the functionality of the Winsock control, and the powerful feature of VB programming is displayed by this example. In this example, the space is not allowed to improve the wrong capture, safety inspection, etc., and it is necessary to pay attention in the practical process.
In addition, this example is limited to communication between two machines. By adding a plurality of Winsock instances, set the corresponding port, we can allow multiple people to "log in" to the server, truly implement the function of chat room, and there is no need to spend huge amount. Internet access, you can "enjoy" to the Internet service. Moreover, this program can also be used on the Internet to communicate information, by setting the port agreed by the friends, you can start the customer or server program after the Internet, online "instant (letter)".
The above programs are passed on the PWIN98 system, VB5.0. In fact, we can also use this control for VFP, VC, PB, etc. Support ActiveX control. In this throwing brick, improper, hopes that all the colleagues are advised.
==
1998? 1999? Written, don't remember