Joke Collection Website - Blessing messages - How to use socket control in VB6.0?
How to use socket control in VB6.0?
Socket was put forward on Unix system. At first, it was mainly used for local communication, but it was quickly applied to C/S systems. On this basis, Microsoft created WinSock control, which is specially used for Windows interface and fully compatible with Sockets. Winsock control is invisible to users, and it provides a convenient way to access TCP and UDP network services. Developers of Microsoft Access, Visual Basic, Visual C++ or Visual FoxPro can use it. To write a client or server application, you don't need to know the details of TCP, and you don't need to call the underlying Winsock APIs. By setting the properties of the control and calling its methods, you can easily connect to a remote computer and exchange data in both directions. Write an online chat program with WinSock control in VB5.
1) The basis and selection of network communication protocols
1. 1 TCP (data transfer protocol) basis
Data transfer protocols allow you to create and maintain connections with remote computers. Connecting two computers can transmit data to each other.
If you create a client application, you must know the server computer name or IP address (RemoteHost property) and the listening port (RemotePort property), and then call the Connect method.
If you create a server application, you should set a listening port (LocalPort property) and call the listen method. The ConnectionRequest event occurs when a client computer needs to connect. To complete the connection, you can call the Accept method in the ConnectionRequest event.
After the connection is established, any computer can send and receive data. To SendData, you can call the senddata method. The DataArrival event occurs when data is received. You can get the data by calling the GetData method in the DataArrival event.
1.2 UDP (user datagram protocol) basis
User Datagram Protocol (UDP) is a connectionless protocol. Unlike TCP, computers do not establish connections. In addition, UDP applications can be clients or servers.
In order to transmit data, you must first set the LocalPort property of the client computer. Then, the server computer only needs to set the RemoteHost to the Internet address of the client computer, set the RemotePort property to the same port as the LocalPort property of the client computer, and call the SendData method to start sending information. Therefore, the client computer uses the GetData method in the DataArrival event to get the sent information.
1.3 Select the communication protocol
When using WinSock control, the first thing to consider is what protocol to use. Protocols that can be used include TCP and UDP. The important difference between these two protocols lies in their connection status:
TCP protocol is a connection protocol, which can be compared with telephone system. Before starting data transmission, users must establish a connection.
UDP protocol is a connectionless protocol, and the transmission between two computers is similar to the delivery of mail: messages are sent from one computer to another, but there is no clear connection between them. In addition, the maximum amount of data transmitted at a time depends on the specific network.
Which protocol you choose is usually determined by the application you need to create. The following questions will help you choose the right protocol:
1. Does the application need to get confirmation information from the client or server when sending and receiving data? If necessary, before sending and receiving data, establish a clear connection using TCP protocol.
2. Is the amount of data extremely large (such as images and sound files)? After the connection is established, the TCP protocol will maintain the connection and ensure the integrity of the data. However, this connection requires more computing resources, so it is "expensive".
3. Is the data transmission intermittent or in a session? For example, if an application needs to notify the computer when a task is completed, UDP protocol is more suitable. UDP protocol is suitable for sending a small amount of data.
The choice of communication protocol is realized by setting the protocol properties of WinSock. Choose TCP communication protocol to write online chat program. Before that, you must know an extremely important parameter-the IP address or computer name of the server.
2) Determine the name of the computer
1. On the computer desktop, right-click My Network Places.
2. Select "Properties".
3. Click the logo tab.
4. You can find the name of the computer in the Computer Name box.
Determine the IP address of the computer
1. Click Start on the taskbar.
2. Select "Run".
3. If the server-side operating system is win95, fill in "winipcfg" in "Open" and "ipconfig" in "Open" if the server-side operating system is winnt.
4. Press the "OK" key.
The computer name or IP address found above can be used as the value of WinSock's RemoteHost property.
State properties of winsock controls.
The set value of the state property is: constant.
Value description
Sckclosed 0 default value. close
Sckopen 1 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.
Sckclosing 8 peer is closing the connection.
Sckerror 9 error
The following mainly uses the values of two status attributes: sckClosed.sckConnected.
4) Programming of online chat program
4. 1 The role of the server in the program.
As can be seen from the figure, there is no direct communication between the two winsock controls on the server side, and there is no direct communication between sckServer 1 and sckClient2 and between sckServer2 and sckClient 1. That is, if sckClient 1 sends a message to sckClient2, the message is first accepted by sckServer 1 and then transmitted to the information processing part of the program, and the information processing part transmits the processed message to sckServer2 and then to sckClient2. And vice versa, from Dallas to the auditorium, what does the information processing part of the server do?
1. Make some restrictions on the number of communication channels.
2. Closed channels must be reused to save resources.
3. The transmitted packet information must be distinguished for different processing.
Different information can be distinguished by the header of unpacked data.
There are two ways to chat online: one is through broadcasting; Second, in a point-to-point manner. Broadcast mode means that all customers can receive the information sent by one customer. Peer-to-peer mode means that a pair of customers who want to "whisper" have a special "cabin" to talk, and other customers can't "listen" to their conversation. In the following program, we will see how to use different data headers (the header of point-to-point data is "PT" and the broadcast mode has no header) to distinguish whether users want to talk in broadcast mode or point-to-point mode.
4.2 client program
1. Create a new project on the client and name it "ClientPrj".
2. Name the default form frmClient.
3. Change the title of the form to "Customer".
4. Add a WinSock control to the form and name it tcpClient.
5. Add ListBox control in frmClient. Name it lstReceive.
6. add TextBox control in frmClient. Named txtSend.
7. Place two CommandButton controls on the form and name them cmdConnect and cmdSent.
8. change the title of cmdConnect control to Connect, and change the title of cmdSent control to Sent.
9. Add the following code to the form.
Private Sub cmdConnect_Click()
Go to the error prompt when an error occurs.
sckClient。 connect
outlet connection
Error prompt:
MsgBox "The server is not turned on or there is a network error!"
end
End joint
Private Sub cmdSent_Click()
sckClient。 SendData txtSent。 text
End joint
Private Sub-Form _Load ()
RemoteComputerName is the computer name or IP address of the server.
sckClient。 RemoteHost = "RemoteComputerName "
sckClient。 Remote port = 1000
End joint
Private Sub sckClient_Close ()
MsgBox "Server channel closed!"
end
End joint
Private Sub sckClient_Connect ()
MsgBox "Connection successful!"
cmdConnect。 Enabled = False
End joint
private Sub sck client _ data arrival(ByVal bytes total As Long)
Darken s as a string
sckClient。 GetData s
lstReceive。 Additional item
End joint
Private subckclient _ error (byvalnumber is an integer, Description is a string, ByVal Scode is a Long, _ ByVal Source is a string, ByVal HelpFile is a string, ByVal HelpContext is a Long, and CancelDisplay is a Boolean).
sckClient。 close
cmdConnect。 Enabled = true
End joint
4.3 Server-side program
1. Create a new project on the server side and name it "ServerPrj".
2. Name the default form "frmServer".
3. Add a ListBox control to the form and name it "lstReceive".
4. Add three WinSock controls to the form, named "sckListen", "sckBusy" and "sckServer" respectively, and set the "Index" property of "sckServer" to 0.
5. Add the following code to the form.
Maximum number of channels
Private MaxChan is an integer.
Private Sub-Form _Load ()
Mark I as an integer
MaxChan = 10
For i = 1 to MaxChan-1
Load sckServer(i)
Next, I
sckListen。 Local port = 1000
sckListen。 listen to
End joint
Private Sub sckBusy_Close ()
sckBusy。 close
End joint
private Sub sck busy _ data arrival(ByVal bytes total As Long)
SckBusy。 SendData "The server is busy, please connect later!"
Multiple activities
End joint
Private subcklisten _ connectionrequest (byval request id is Long)
Mark I as an integer
Decide which Winsock will accept the request.
For i = 0 to MaxChan-1
If sckServer(i). Then state = 0
Quit for ...
If ... it will be over.
Next, I
If sckServer(i). Then state = 0
sckServer(i)。 Accept requestID
outlet connection
If ... it will be over.
If all Winsock is used up, a special "busy" Winsock will accept the request in case the user's request is not answered.
sckBusy。 close
sckBusy。 Accept requestID
End joint
Private subcklisten _ error (byval number is an integer, Description is a string, ByVal Scode is a Long, _ ByVal Source is a string, ByVal HelpFile is a string, ByVal HelpContext is a Long, and CancelDisplay is a Boolean).
sckListen。 close
sckListen。 Local port = 1000
sckListen。 listen to
End joint
Private Sub sckServer_Close (index is an integer)
SckServer (index). close
End joint
Private subsckserver _ dataarrival (index is an integer, ByVal bytesTotal is a long integer)
Darken s as a string
Mark I as an integer
SckServer (index). GetData s
Ifucase (left (trim (s), 2)) = "pt" and then' judge whether it is a whisper, point-to-point way.
If IsNumeric(Mid(Trim(s), 3, 1)), then
i = Mid(Trim(s),3, 1)
sckServer(i)。 Send data channel. Index and index. & Right (Trim), Lens (Trim)-3)
Multiple activities
If ... it will be over.
"Else" broadcast mode
For i = 0 to MaxChan-1
Use winsock's State property to send messages to all clients connected to the server.
If sckServer(i). Then state = 7
sckServer(i)。 Send data channel. Index and index. "& Trim
Multiple activities
If ... it will be over.
Next, I
If ... it will be over.
lstReceive。 AddItem channel Index and index. "& Trim
End joint
Private subckserver _ error (index is an integer, ByVal number is an integer, Description is a string, _
Byvalscope is Long, ByVal source is String, ByVal help file is String, and ByVal help context is _
Long, cancel is displayed as a boolean value)
SckServer (index). close
End joint
It can be seen from the program: First, the number of channels is limited in the program (10 channels). Second, reuse the closed WinSock control by judging whether the State property of the WinSock control is 0 (closed state). Thirdly, by adding a header to the information sent by the WinSock control, the information can be treated differently (if the header of "PT" (private chat)+"number of channels" is added before the information in the program, you can know that the customer wants to "whisper" with another customer who has this number of channels, otherwise the information will be sent to all customers by broadcasting).
V) Concluding remarks
WinSock control can be used not only to write online chat programs, but also to write various online games or network communication programs. In fact, WinSock control is a powerful tool for compiling various C/S programs. In practice, WinSock controls are usually encapsulated in classes of Activex DLL (in-process) and Activex EXE (out-of-process) components (referenced in classes). By distinguishing different headers in front of the transmitted information, different events are triggered by the RaiseEvent command, and then the events are handled separately. This not only improves the debugging and security of the program, but also conforms to the characteristics of event-driven programming method.
- Previous article:How to use miles to upgrade Shenzhen Airlines
- Next article:Give some personal experiences of dopod P4550.
- Related articles
- A newspaper that attracts investment needs a strong headline.
- Fairy sentences recorded by classmates
- Qi Pa Shuo program contact information
- A 500-word weekly diary of five selected New Year greetings on the first day of junior high school.
- Close contacts are isolated at home for a few days and taken to a centralized isolation point. Is the corridor about to be unsealed?
- Notice of Fuyang Science and Technology Museum on Prevention and Control Measures of Epidemic Situation
- I agreed to leave my job in the text message, and then I found the legal basis. Can I deny leaving my job?
- What if I accidentally opened a pornographic short message?
- Hohhot endowment insurance inquiry personal account
- Discover the corruption of unit leaders