Current location - Loan Platform Complete Network - Big data management - How to use socket control in VB6.0?
How to use socket control in VB6.0?
Writing Online Chat Programs with the WinSock Control in VB5

Sockets were introduced on Unix systems, primarily for local communication at first, but were soon applied to C/S systems.MicroSoft created the WinSock control on this basis, specifically for the Windows interface, which is fully compatible with Sockets.The Winsock control is invisible to the user and provides easy access to TCP and UDP network services. The Winsock control is invisible to the user and provides easy access to TCP and UDP network services and can be used by developers of Microsoft Access, Visual Basic, Visual C++ or Visual FoxPro. To write client or server applications without having to know the details of TCP or calling low-level Winsock APIs, you can easily connect to a remote machine and exchange data in both directions by setting the control's properties and calling its methods. The following is the use of VB5 WinSock control to write an online chat program.

I) the basis of network communication protocols and the choice

1.1 TCP (Data Transfer Protocol) basis

Data Transfer Protocol allows the creation and maintenance of connections to remote computers. Connecting two computers allows them to transfer data to each other.

If you create a client application, you must know the name or IP address of the server computer (the RemoteHost property) and the port on which you are "listening" (the RemotePort property), and then call the Connect method.

If you create a server application, you set a listening port (LocalPort property) and call the Listen method. The ConnectionRequest event occurs when the client computer needs to connect. To complete the connection, call the Accept method within the ConnectionRequest event.

After a connection is established, either computer can send and receive data. To send data, the SendData method is called. The DataArrival event occurs when data is received. The GetData method within the DataArrival event is called to get the data.

1.2 Fundamentals of UDP

User Datagram Protocol (UDP) is a connectionless protocol. Unlike the operation of TCP, computers do not establish a connection. Also UDP applications can be clients or servers.

In order to transfer data, the client computer first sets the LocalPort property. The server computer then simply sets RemoteHost to the client computer's Internet address, sets the RemotePort property to the same port as the client computer's LocalPort property, and calls the SendData method to begin sending the information. The client computer then uses the GetData method within the DataArrival event to retrieve the sent information.

1.3 Choosing a communication protocol

When working with the WinSock control, the first thing you need to consider is what protocol to use. The protocols that can be used are TCP and UDP. The important difference between the two protocols is their connection status:

The TCP protocol is a connected protocol, which can be compared to the telephone system. The user must establish a connection before data transmission can begin.

The UDP protocol is a connectionless protocol, and transfers between two computers are similar to sending mail: messages are sent from one computer to another, but there is no explicit connection between the two. Also, the maximum amount of data that can be transferred in a single transmission depends on the specific network.

The exact choice of protocol is usually determined by the application that needs to be created. The following questions will help in choosing the appropriate protocol:

1. Does the application need to get an acknowledgement from the client or server when sending or receiving data? If so, use the TCP protocol to establish a clear connection before sending or receiving data.

2. Is the amount of data particularly large (e.g., image and sound files)? After the connection is established, the TCP protocol maintains the connection and ensures the integrity of the data. However, such connections require more computational resources and are therefore more "expensive.

3. Is data sent intermittently, or within a session? For example, if an application needs to notify a computer when a task has been completed, the UDP protocol is more appropriate; UDP is good for sending small amounts of data.

The choice of communication protocol is made by setting the Protocol property of WinSock. The following TCP protocol is chosen to write an 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 desktop of the computer, right-click "Online Neighborhood".

2. Select Properties.

3. Click the Identity tab.

4. You can find the name of the computer in the Computer Name box.

Determining the IP address of the computer

1. Click Start on the Taskbar.

2. Select Run.

3. Enter "winipcfg" in the "Open" field for Win95 server-side operating systems, or "Open" in the "Open" field for Winnt server-side operating systems. If the server operating system is winnt, fill in "ipconfig" in the "Open" field.

4. Press OK.

The computer name or IP address found above can be used as the value for WinSock's RemoteHost property.

Three) The State property of the winsock control.

The state property is set to the following values: Constant

Value Description

sckclosed 0 Default. Closed

sckopen 1 Open

scklistening 2 Listening

sckconnectionpending 3 Connection pending

sckresolvinghost 4 Identified host

sckhostresolved 5 Identified host <

sckconnecting 6 Connecting

sckconnected 7 Connected

sckclosing 8 Peer is closing the connection

sckerror 9 Error

The following is mainly going to be used with the scckClosed.scckConnected values of the two State properties.

4) Programming an online chat program

4.1 The role played by the server side of the program.

From the illustration, you can see that there is no direct communication between the two winsock controls on the server side, and there is no direct communication between scckServer1 and scckClient2 and scckServer2 and scckClient1. This means that if scckClient1 sends a message to scckClient2, the message is first accepted by scckServer1, which then passes the message to the information processing part of the program, which then passes the processed message to scckServer2, which then passes it from scckServer2 to scckClient2. And vice versa. So what does the server-side information processing part do?

1. Some limits are placed on the number of channels that can be communicated.

2. Channels that are closed after use must be able to be reused to save resources.

3. The packet information passed must be categorized so that it can be handled differently.

Different information can be distinguished by unpacking the packet headers of the data.

There are two ways of chatting on the Internet: the first, by broadcasting, and the second, by peer-to-peer. Broadcast means that all clients receive messages from a particular client. The point-to-point approach that want to say "whisper" a pair of customers to open a special conversation "cabin", other customers can not "hear" their conversation. In the following program will see how to use the data of different packet headers to distinguish between the user wants to broadcast or point-to-point way to talk (point-to-point way data packet header for the "PT", the broadcast method is no header).

4.2 The client program

1. Create a new project on the client side and name it "ClientPrj"

2. Name the default form frmClient.

3. Change the title of the form to "Client".

4. Add a WinSock control to the form and name it tcpClient.

5. Add a ListBox control to frmClient. Name it lstReceive.

6. Add a TextBox control to frmClient. Name it txtSend.

7. Put two CommandButton controls on the form and name them cmdConnect and cmdSent.

8. Change the title of the cmdConnect control to Connect, and change the title of the cmdSent control to Sent.

9. p>9. Add the following code to the form.

< p>Private Sub cmdConnect_Click()

< p>On Error GoTo ErrorPro

< p>sckClient.Connect

< p>Exit Sub

< p>ErrorPro:

< p>MsgBox " Server not on or network error!"

End

End Sub

Private Sub cmdSent_Click()

sckClient.SendData txtSent.Text

End Sub

Private Sub Form_ Load()

' RemoteComputerName is the server-side computer name or IP address.

sckClient.RemoteHost = "RemoteComputerName"

sckClient.RemotePort = 1000

End Sub

Private Sub sckClient_Close()

MsgBox "Server channel closed!"

End

End Sub

Private Sub sckClient_Connect()

MsgBox "Connection successful!"

cmdConnect.Enabled = False

End Sub

Private Sub sckClient_DataArrival(ByVal bytesTotal As Long)

Dim s As String

sckClient.GetData s

lstReceive.AddItem s

End Sub

Private Sub sckClient_Error(ByVal Number As Integer, Description As String, ByVal Scode As Long, _ ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)

sckClient. Close

cmdConnect.Enabled = True

End Sub

4.3 Server Side Programs

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, name them "sckListen", sckBusy, and "sckServer" and set the " sckServer" and set the "Index" property of " sckServer" to 0.

5. Add the following code to the form.

'MaxChan As Integer

Private MaxChan As Integer

Private Sub Form_Load()

Dim i As Integer

MaxChan = 10

For i = 1 To MaxChan - 1

Load sckServer(i)

Next i

sckListen.LocalPort = 1000

sckListen.Listen

End Sub

Private Sub sckBusy_ Close()

sckBusy.Close

End Sub

Private Sub sckBusy_DataArrival(ByVal bytesTotal As Long)

sckBusy.SendData "Server is busy, please connect later!"

DoEvents

End Sub

Private Sub sckListen_ConnectionRequest(ByVal requestID As Long)

Dim i As Integer

'Determines which Winsock Accepts Request

For i = 0 To MaxChan - 1

If sckServer(i).State = 0 Then

Exit For

End If

Next i

If sckServer(i). State = 0 Then

sckServer(i).Accept requestID

Exit Sub

End If

'If all the Winsocks are exhausted then a specialized "busy" Winsock to accept requests so that user requests do not go unanswered

sckBusy.Close

sckBusy.Accept requestID

End Sub

Private Sub sckListen_Error(ByVal Number As Integer, Description As String, ByVal Scode As Long, _ ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)

sckListen.Close

sckListen.LocalPort = 1000

sckListen.Listen

End Sub

Private Sub sckServer_Close( Index As Integer)

sckServer(Index).Close

End Sub

Private Sub sckServer_DataArrival(Index As Integer, ByVal bytesTotal As Long)

Dim s As String

Dim i As Integer

sckServer(Index).GetData s

If UCase(Left(Trim(s), 2)) = "PT" Then 'Determine if it's a whisper, point-to-point Way

If IsNumeric(Mid(Trim(s), 3, 1)) Then

i = Mid(Trim(s), 3, 1)

sckServer(i).SendData "Channel " & Index & " " &. Right(Trim(s), Len(Trim(s)) - 3)

DoEvents

End If

Else 'Broadcast Method

For i = 0 To MaxChan - 1

'Use the State property of winsock to send a message to all clients connected to the server. Send messages to all clients connected to the server

If sckServer(i).State = 7 Then

sckServer(i).SendData "Channel " & Index & " " & Trim(s)

DoEvents

End If

Next i

End If

lstReceive.AddItem "Channel " & Index & " " & Trim(s)

End Sub

Private Sub sckServer_Error(Index As Integer, ByVal Number As Integer, Description As String, _

ByVal Scode As Long, ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As _

Long, CancelDisplay As Boolean)

sckServer(Index).Close

End Sub

From the program, you can see that: first, the program limits the number of channels (10). Second, you can reuse a closed WinSock control by determining whether the State property of the WinSock control is 0 (closed state). Third, by adding a header to the message passed to the WinSock control, the message is processed differently (in the program, if the message is preceded by the header "PT" (Private Talk) + "Number of Channels", then you know that the customer wants to communicate with another customer who has the "Number of Channels"). "(otherwise the message is broadcast to all customers).

V) Conclusion

WinSock control is not only used to create online chat programs, but also can be used to create a variety of online games or network communication programs. In fact, WinSock control is a powerful tool for programming various C/S programs. In practice, WinSock controls are usually encapsulated in Activex DLL (in-process), Activex EXE (out-of-process) components of the class (class reference) to use. The RaiseEvent command raises different events by distinguishing different headers before the passed information and then handles the events separately. This not only increases the debuggability and security of the program, but also is more in line with the event-driven programming approach.