WinSock programming in VB

Source: Internet
Author: User

 

WinSock programming in VB

 

I. Introduction

Socket originally meant "socket", which is used for computer communication to represent a point-to-point information transmission. Early communication programming specifications were used on Unix systems. The communication parties were composed of two "servers" and "customers" representing two points, and information exchange was conducted based on the IP protocol according to the TCP or UDP specifications. The communication process between the two parties is called the establishment of a "socket". After the establishment, the "socket" is used to exchange various information. With the popularity of the Windows system, some people started to port on the Windows platform. In the early days, Microsoft Compiled a "socket" programming API Based on Windows features (such as message drivers), which is generally called "Winsock API ". After Microsoft's ActiveX technology became popular, Microsoft provided an ActiveX control called "Winsock", facilitating programmers who used vbprogramming to program "socket, this allows point-to-point communication without going into the socket details.

Next, let's first touch this control.

 

Ii. winsocket control details

This control is invisible to users during runtime, provides a simple way to access TCP and UDP network services without having to understand the underlying details. You only need to set properties and call the methods it provides when appropriate.

Main attributes include:

Bytesreceived: returns the number of bytes in the Current Buffer. We can use the getdata method to receive data. Read-only and unavailable during design.

Localhostname: returns the local name string, which is unavailable during design.

Localip: returns an IP address string expressed in the format of (XXX. XXX. Unavailable during design and read-only during running.

Localport: The address used by the local machine. It can be read and written, and can be used in design. It is of the long type. If you do not need to specify a port, use port 0 to send data. In this case, the control selects a random port. After a connection is determined, it is the TCP port. A server is a port used for listening. If it is set to 0, a random number is used. After the listen method is called, this attribute automatically contains the port used. Port 0 is always used to establish a dynamic connection between two computers. The customer wants to obtain a random port through port 0 and "Callback" to connect to the server.

Protocol: socket type, which is either TCP or UDP. The default value is TCP. Scktcpprotocol indicates TCP sckudpprotocol indicates UDP. You must close this property before resetting it.

Remotehost: the host that sends or receives data. You can provide a host name such as "ftp: // ftp.microsoft.com" or an IP address string such as "100.0.1.1 ".

Remotehostip: the IP address of the remote host. For a client program, use the connect method after the connection is confirmed. This attribute contains the IP name string of the remote host. For a server program, this attribute contains an IP string after the connection requirement is introduced (connectionrequest event. When a UDP socket is used and the dataarrival event occurs, this attribute is the IP address string of the machine that sends UDP data.

Remoteport: Specifies the port value of the socket. For example, HTTP applications usually use port 80, and FTP uses port 21.

State: the status of the control, read-only and unavailable during design. You can set the following values:

 

Constant description

Sckclosed 0 default value: Disable socket

Sckopen 1 open socket

Scklistening 2 positive listening port

Sckconnectionpending 3 is establishing an undetermined connection

Sckresolvinghost 4 is parsing the host address

Sckhostresolved 5 Host address resolved

Sckconnecting 6 is connecting

Sckconnected 7 connected

Sckclosing 8 Connection closed

Sckerror 9 Error

Other properties are similar to general controls.

The main methods are as follows:

Accept: used only for TCP server applications. This method is used to respond to the connectionrequest event when a connection is introduced. Syntax: object. Accept requestid return value: void. When responding to an event, you must pass the requestid parameter to this method to generate a new socket instance for actual information transmission.

BIND: Set localport and localip for TCP connection. It is used when you have multiple Protocol adapters. Syntax: object. Bind localport, localip. Localport: This port is used for connection. localip generates the IP address of the connection. If you have set relevant attributes, you do not need to include relevant parameters. Call this method before calling the lisent method.

Close: Close the TCP connection on the client or server. Syntax: object. Close. Parameter: none. Return Value: void.

Getdata: receives data blocks stored in a variable type. Return Value: void. Syntax: object. getdata data, [type,] [maxlen]. Data: The variable that receives data. If there is not enough space, it is set to null. Type: Optional. Type of the message to be received. Set it by yourself. Maxlen: an optional parameter. Set the size of the received array or string type data. If the parameter is missing, all data is received. This parameter is ignored if data types other than arrays or strings are provided. Type can be set to a common data type. This method is usually used in dataarrival events. This event contains the totalbytes parameter. If the maxlen you set is smaller than the totalbytes parameter, you will get a warning message that the remaining bytes represented by 10040 will be lost.

Listen: Creates a socket set to the listening mode. This method is only used for TCP connections. Syntax: object. Listen

Parameter: none. Return Value: void. A connectionrequest event occurs when a connection is introduced after listen is called. When handling connectionrequest, the application must use the 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. Syntax: object. peekdata data, [type,] [maxlen]

 

Senddata: sends a host to the remote host. Return Value: void. Syntax: object. senddata data. Data: The data to be sent, using a byte array. Unicode strings are converted to ANSI strings before being sent.

The following events occur:

Close: the connection is closed on the remote host. The close method should be used to close TCP connections correctly.

Connect: when the connection operation is complete. Syntax: object. Connect (). This event indicates that the connection is successful.

 

Connectionrequest: occurs when a remote host requires a connection. Only used for TCP server applications. The remotehostip and remoteport attributes store information about the client after this event. Syntax: object_connectionrequest (requestid as long ). Requestid: The request ID of the introduced connection. This parameter is passed to the second control instance in the accept method. The server can decide whether to approve the connection. If the introduced connection is not accepted, the customer will receive a close event. Use the accept method to accept the introduced connection.

Dataarrival: occurs when new data arrives. Syntax: object_dataarrival (bytestotal as long ). Bytestotal, long type. Total amount of data received. This event will not occur until you call the getdata method. Activated only when new data arrives. You can use the bytesreceived attribute to check how much data is valid at any time.

Error: indicates an error has occurred. The error code is ignored.

Sendcomplete: occurs when the sending action is complete. Syntax: object_sendcomplete. Parameter: none.

Sendprogress: this event is generated when data is sent. Syntax: object_sendprogress (bytessent as long, bytesremaining as long ). Bytessent: the amount of data sent since the occurrence of this event. Bytesremaining: The data to be sent in the buffer.

 

Iii. winsocket Programming Application Example

We can see that the winsocket control allows us to use two transmission protocols for communication. The TCP protocol allows you to establish and maintain connections with the remote host, and both parties can transmit data in stream mode. In this way, the customer must know the name of the server (remotehost attribute), The remoteport of the server listening (Listening), and then call the connect method. The server program must set the scoket listening port (localport) and then call the listen method. When the client requests a connection, the server generates a connectionrequest event. If the server wants to complete the connection, the accept method is called for approval. Once the connection is established, both computers can use the senddata method to send messages. When data is received, the dataarrival event occurs. In this event, we can call the getdata method to receive data. If UDP is used, the client sets the local listening port (localport attribute), the server computer sets the client name (remotehost), and the listening port attribute (remoteport ), then you can call the senddata method to send data. The client uses the getdata method to receive information in the dataarrival event.

To demonstrate the programming details, we compile a "chat" Application for two people: the program is divided into two independent parts: the customer and the server. First, start the server application, then start the client program, establish a connection after handshaking, and then both parties can communicate with each other. TCP protocol can be used to achieve real-time and accurate information transmission.

The procedure is as follows:

Write the server program:

Create a standard project, and select components… under the project ..., Select Microsoft WinSock control 5.0 from the displayed dialog box. After confirmation, a control named winscok is added to the control panel. This control is the "master" in this article ".
Change the form1 caption attribute to "socksrv" and add the Winsock control that just added the project to the form.
Add three label and textbox controls, one command control, and set their attributes and functions as follows:
Label1.caption = "listening port:", label2. caption = "customer message:", label3. caption = "Server Message :"

Textbox1.text = "900", which is used to set the server listening port of WinSock.

Textbox2.text = "", textbox2. multilin = ture, textbox2.scrollbar = 2. By setting the text attribute to a space, the control can set the initial information to blank. The multilin attribute to true allows multiple lines to be displayed, and the communication between the server and the customer can be displayed in real time. Set scrollbar to 2. You can add a vertical scroll bar to display information of multiple rows. The main function of this control is to display the communication content between servers and customers in real time.

The Property setting of textbox3 is the same as that of textbox2. It mainly serves to input the user information of the server.

The title of command1 is "listener", which is used to switch the server to the Connection Request status of the listening port.

Add the Code as follows:
Add winsock1.localport = text1.text in the form1.load event to set the listening port defined by text1 to the Winsock Control.

In the click event of command1, add:

 

If winsock1.state <> sckclosed then winsock1.close 'is disabled when the current socket is not closed

Winsock1.bind' takes effect

Winsock1.listen 'listener port connection request

Add code to several winscok events:

Private sub winsock1_connectionrequest (byval requestid as long)

If winsock1.state <> sckclosed then winsock1.close

Winsock1.accept requestid 'Call the accept method immediately when a connection request occurs on the listening port

'Approve the connection to make it take effect.

End sub

Private sub winsock1_dataarrival (byval bytestotal as long)

Dim strdata as string

Winsock1.getdata strdata, vbstring when data arrives, call the getdata method to receive

Text2.text = strdata' displays received content updates in text2

End sub

 

The above is to set the server side. Next let's take a look at the client program.

Create a new standard project and add the Winsock control to the control panel according to the method above.
Modify the project name "sckclient" and add the Winsock control to the form.
Add three label and text controls and two command controls whose attributes are:
Label1.caption = "server address:", label2.caption = "server sent information", label3.caption = "customer message ".

Text1.text = "www.ysh.com", which is the address or name of the server to be communicated with by the customer. enter the name of the server or the IP address of the TCP/IP protocol during actual operation. Www.ysh.com is my host name on my LAN.

Text2.multilin = true, which is used to display the information sent by the server in multiple rows. To view all the information sent by the server, set the scollbar attribute to 3.

Text3 should also be a control that allows multi-line display.

The caption of command1 and comand2 is "connection" and "disconnected", respectively, to determine the Winsock connection status.

Add the corresponding code:
In form_load (), enter winsock1.remoteport = "900" to determine the port on which the socket is created on the same server.

In commandemediclick (), enter:

If winsock1.state <> sckclosed then winsock1.close 'If the socket is not closed, close it first

Winsock1.remotehost = text1.text 'determine the server host name

Winsock1.bind' bind the socket Property

Winsock1.connect 'sends a connection request to the server

Command1.enabled = false' make command1 unavailable

Command2.enabled = true' can be disconnected now

 

Enter the code in command2_click:

Command1.enabled = true

Command2.enabled = false

Winsock1.close 'close current socket

For various events of the Winsock Control, refer to the following code:

Private sub winsock1_dataarrival (byval bytestotal as long)

Dim STR as string

Winsock1.getdata STR, vbstring 'receives information based on the string type

Text2.text = STR 'Update to text2 now

End sub

Private sub winsock1_connect () '. The message box is displayed after the connection is successful.

Msgbox "connected to server! "

End sub

In order to reflect the content of text3 to the server information box in real time, text3_change () needs to input the following code:

If winsock1.state = sckconnected then winsock1.senddata text3.text

 

Through the above settings and writing, the actions of both the server and the client are completed, so that we can communicate over the network. Start the server, press the "Connect" button, wait for the client's request, start the customer, enter the correct server address or host name, and press the "Connect" button. When a message box pops up, this indicates that the connection is successful. At this time, no matter whether you enter any information in the server or the customer's text3, it will be displayed in the other party's text2 in real time, so that a simple "chat" program starts to work normally.

 

 

Iv. program description

Some skills are required to debug the above programs. Because the Winsock Control is a network-based control, the network must be properly installed on the machine for debugging and running, and the TCP/IP protocol must be installed; at the same time, because the application is based on the C/S mode, it is necessary to run two processes at the same time or run on two machines that have been connected through the TC/IP protocol. Debugging on a single machine requires some skills. We can start two VB Programs at the same time, open two projects, customer and server, and start them through task switching after design. In this way, you can use Windows 95 to perform network simulation on a single machine.

This program is just a simple demonstration of the Winsock control function, through this example shows the powerful functions of VB programming. In this example, measures such as error capture and security check are not completed in detail due to the length constraints. You must pay attention to these measures during practical use.

In addition, this example only supports communication between two machines. By adding multiple Winsock instances and setting corresponding ports, we can allow multiple users to "Log on" to the server at the same time, to truly implement the functions of the chat room, there is no need to spend a huge amount of Internet fees, you can "enjoy" Internet services. In addition, this program can be used by two machines on the Internet to exchange information. By setting a port agreed with a friend, you can start a client or server program after going online, click "instant messaging" on the Internet )".

The above program passes through the pwin98 system and VB5.0. In fact, we can also use this control in languages that support ActiveX controls such as VFP, Vc, and Pb. In this case, I hope you will give me some advice.

=

1998? 1999? I can't remember it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.