Client Server Programming With Winsock
Client Server Programming With Winsock
Client Server Programming With Winsock
Security
Tutorials
Download.zip
Introduction
Winsock control comes with VB6 and is used to create applications that access the low-level functions of the Transmission Control Protocol/Internet Protocol (TCP/IP). Most of you might have worked with Internet Transfer Control which is very handy control when it comes to Internet Programming but there is another control which even more robust and helps programmers creating more flexible applications. Winsock control comes with VB6 and is used to create applications that access the low-level functions of the Transmission Control Protocol/Internet Protocol (TCP/IP). TCP/IP is a specification that defines a series of protocols used to standardize how computers exchange information with each other. TCP/IP provides communication across interconnected networks that use diverse hardware architectures and various operating systems. The protocols in TCP/IP are arranged in a series of layers known as a protocol stack. Each layer has its own functionality. Winsock is a standard that is maintained by Microsoft. This standard is basically a set of routines that describe communications to and from the TCP/IP stack. These routines reside in a dynamic link library that runs under Windows. The winsock DLL is interfaced with TCP/IP and from there through the Internet. In this article, I am going to show how to use the winsock in a client server environment, we will create two separate applications, one of which will be a server and the other will be a client. Both client and server will interact with each other to exchange data. Client will send a request to the server and the server which will be connected to a database will retrieve the information requested by the client from the database and will return the requested information back to the client. You will a database with this article, the database contains the item numbers and their prices. In real life situations, database might be located on a machine different from the one that hosts the client application.
Local loops/callbacks 0
sckTCPProtocol sckUDPProtocol
BytesReceived Property
This property returns the number of bytes currently in the receive buffer. This is a read-only property and is unavailable at design time. The value returned is a long integer.
LocalHostName Property
The LocalHostName property returns the name of the local host system. This is read-only property and is unavailable at the design time. The value returned is a string.
LocalIP Property
The LocalIP property returns the local host system IP address in the form of a string, such as 11.0.0.127. This property is read-only and is unavailable at design time.
LocalPort Property
This property returns or sets the local port number. This can be both read from and written to and is available at both design time and runtime. The value returned is a long integer.
Protocol Property
Returns or sets the protocol, either TCP or UDP, used by the Winsock control.
RemoteHost Property
The RemoteHost property returns or sets the remote host. This can be both read from and written to and is available both in design time and runtime. The value returned is a string and can be specified either as an IP address or as a DNS name.
RemotePort Property
This property returns or sets the remote port number.
State Property
This returns the state of the control as expressed by an enumerated list. This is read-only property and is unavailable at design time. Some of the important methods of Winsock control are as following:
Accept Method
It accepts the request for connection from the client system. For this method to be used, the control must be in the listening state.
Close Method
The Close method terminates a TCP connection from either the client or server applications.
GetData Method
GetData is the method that retrieves the current block of data from the buffer and then stores it in a variable of the variant type.
PeekData Method
The PeekData method operates in a fashion similar to the GetData method. However, it does not remove data from the input queue.
Listen Method
This is invoked on the server application to have the server application wait for a TCP request for connection from a client system.
SendData Method
This method dispatches data to the remote computer. It is used for both the client and server systems.
Connect Method
The Connect method requests a connection to a remote computer. I am not going to discuss events here. You can find the complete details of events on the Microsoft site.
Else shpGo.Visible = False shpWait.Visible = False shpError.Visible = True Label3.Caption = "Not currently connected to host" End If End Sub Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long) Dim sData As String Winsock1.GetData sData, vbString 'Label1.Caption = sData txtPrice.Text = sData Label3.Caption = "Received Data" shpGo.Visible = True shpWait.Visible = False shpError.Visible = False End Sub Private Sub Winsock1_SendComplete() Label3.Caption = "Completed Data Transmission" End Sub
Follow the steps shown below to create the server: 1. Start a new Standard EXE in VB. 2. Add the Winsock control to your application. 3. Add the controls to the form as shown in the accompanying code (See the folder named as “server”). Here is the complete code:
Option Explicit Dim iSockets As Integer Dim sServerMsg As String Dim sRequestID As String Private Sub Form_Load() Form1.Show lblHostID.Caption = Socket(0).LocalHostName lblAddress.Caption = Socket(0).LocalIP Socket(0).LocalPort = 1007 sServerMsg = "Listening to port: " & Socket(0).LocalPort List1.AddItem (sServerMsg) Socket(0).Listen End Sub Private Sub socket_Close(Index As Integer) sServerMsg = "Connection closed: " & Socket(Index).RemoteHostIP List1.AddItem (sServerMsg) Socket(Index).Close Unload Socket(Index) iSockets = iSockets - 1 lblConnections.Caption = iSockets End Sub Private Sub socket_ConnectionRequest(Index As Integer, ByVal requestID As Long) sServerMsg = "Connection request id " & requestID & " from " & Socket(Index).RemoteHostIP If Index = 0 Then List1.AddItem (sServerMsg) sRequestID = requestID iSockets = iSockets + 1 lblConnections.Caption = iSockets Load Socket(iSockets) Socket(iSockets).LocalPort = 1007 Socket(iSockets).Accept requestID End If End Sub Private Sub socket_DataArrival(Index As Integer, ByVal bytesTotal As Long) Dim Dim Dim Dim sItemData As String strData As String strOutData As String strConnect As String
' get data from client Socket(Index).GetData sItemData, vbString sServerMsg = "Received: " & sItemData & " from " & Socket(Index).RemoteHostIP & "(" & sRequestID & ")" List1.AddItem (sServerMsg) 'strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=G:\Prices.mdb;Persist Security Info=False" Dim strPath As String 'Change the database path in the text file Dim fso As New FileSystemObject, txtfile, _ fil1 As File, ts As TextStream Set fil1 = fso.GetFile("path.txt") ' Read the contents of the file. Set ts = fil1.OpenAsTextStream(ForReading) strPath = ts.ReadLine ts.Close Set fso = Nothing strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Persist Security Info=False;Data Source=" & strPath & _ "; Mode=Read|Write" Dim rs As New ADODB.Recordset ' Get clients request from database strData = "Item = '" & sItemData & "'" rs.Open "select * from prices", strConnect, adOpenKeyset, adLockOptimistic rs.Find strData strOutData = rs.Fields("Price") 'send data to client sServerMsg = "Sending: " & strOutData & " to " & Socket(Index).RemoteHostIP List1.AddItem (sServerMsg) Socket(Index).SendData strOutData End Sub