Click here to Skip to main content
15,882,017 members
Articles / Desktop Programming / MFC
Article

Creating Client/Server Application using Winsock

Rate me:
Please Sign up or sign in to vote.
4.50/5 (28 votes)
4 Nov 20018 min read 355.2K   95.8K   48   26
This article shows you how to use 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.

Sample Image - client.jpg

INTRODUCTION

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. 

I think it would be better to talk about the ports before we proceed any further. A port is a special memory location that exists when two computers are in communication via TCP/IP. Applications use a port number as an identifier to other computers, both the sending and receiving computers use this port to exchange data. 

To make the job of communication easier, some port numbers have been standardized. These standard port numbers have no inherent value other than that users have agreed to use them with certain applications. Table below lists a number of popular and publicly accepted port numbers and their corresponding applications.

Service

Port

HTTP80
FTP20,21
GOPHER70
SMTP25
POP3110
TELNET23
FINGER79
LOCAL LOOPS/CALLBACKS0

Using the Winsock Control

Winsock is above the TCP/IP protocol stack in the ISO/OSI model. TCP/IP is an industry standard communication protocol that defines methods for packaging data into packets for transmission between computing devices on a heterogeneous network. TCP/IP is the standard for data transmission over networks, including the Internet. TCP establishes a connection for data transmission and IP defines the method for sending data packets.

The Microsoft Winsock control makes using the TCP/IP a breeze. Microsoft has wrapped up the Winsock and INetAPI API calls into a nice neat package that you can easily incorporate into your Visual Basic applications.

Winsock Operating Modes

The Transport layer (also known as the Host-to-Host Transport layer) is responsible for providing the Application layer with session and datagram communication services. The core protocols of the Transport layer are TCP and User Datagram Protocol (UDP). The Winsock control supports the following two operating modes:
 

  • sckTCPProtocol
  • sckUDPProtocol

Winsock Properties

Winsock enables you to create clients and servers using the same control. This dual functionality enables you to specify through property setting the type of application you will be building. The Winsock control uses a number of the same properties, whether you are creating client or a server, thereby all but eliminating the learning curve needed to create applications. Some of the important properties of the control are as following:

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.

Winsock Methods

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 (http://www.microsoft.com).

In the sample provided with this article, we are going to create two applications, one server and client. This is a real world example, where the clients requests some information from the server and the server retrieves some specific information from the database and sends the retrieved information back to the client. The database used in the sample is also provided with the code. The database name is Prices.mdb. This is a small database comprising of a single table containing two fields. The fields are item number and price. The clients sends the item number to the server and the server retrieves the price against that item number from the database and sends it back to the client. One of the current trends in software development today is the issue of thick clients versus thin clients. A thick client is basically an application that performs the bulk of the processing on the individual client PC, whereas a thin client performs the processing on the server. 

Creating the Client

Follow the steps shown below:

1. Start a new EXE project.
2. Add a Winsock control to your application.
3. Add all the controls to the form (See the application for details).

Here is the complete code:

Option Explicit

Private Sub cmdClose_Click()
Winsock1.Close
shpGo.Visible = False
shpWait.Visible = False
shpError.Visible = True
End Sub

Private Sub cmdConnect_Click()
Winsock1.RemoteHost = "11.0.0.1" 'Change this to your host ip
Winsock1.RemotePort = 1007
Winsock1.Connect
shpGo.Visible = True
txtItem.SetFocus
End Sub

Private Sub cmdSend_Click()
If Winsock1.State = sckConnected Then
    Winsock1.SendData txtItem.Text
    shpGo.Visible = True
    Label3.Caption = "Sending Data"
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

Creating the Server

The server portion of the price lookup example is designed to accept the item number sent from the client and look up the associated price in a database. The server than sends the information back to the client. There is file named as “path.txt” in the folder called as “server”. Locate that file and change the database path in the file to the location where the database is located on your machine. The connection to the database is made in the DataArrival event of the Winsock control. The following code segment opens the database and finds the first occurrence of the value in sItemData. When the record is found, the value contained in the price field is sent back to the client.

' Get clients request from database

strData = "Item = '" & sItemData & "'"
rs.Open "select * from prices", strConnect, adOpenKeyset,adLockOptimistic
rs.Find strData
strOutData = rs.Fields("Price")

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 sItemData As String
   Dim strData As String
   Dim strOutData As String
   Dim 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

Running the example

1. Create executable for both the applications.
2. Launch both the applications.
3. Click the Connect button.
4. Enter a value from 0 to 6 (currently the database contains only six records, error handling is not done in this code, you can add the error handling yourself) and click the Lookup button. The associated price will be displayed in the price field.

</body>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Pakistan Pakistan
S.S. Ahmed is a senior software engineer and works for a web and software development firm. Ahmed is a Microsoft Office SharePoint Server MVP. Ahmed specializes in creating database driven dynamic web sites. He has been creating customized SharePoint solutions for the last five years. Ahmed has worked in Visual Basic, Visual C, Java, ASP, .NET, SharePoint, InfoPath, BizTalk, etc. Ahmed enjoys travelling and has been to many parts of the world. Ahmed distributes most of his work freely to many internet sites. Ahmed also participates in different newsgroups and tries to help people out with their problems. Ahmed can be reached at share.point@yahoo.com

PEACE

S.S. Ahmed
Web: www.walisystems.com
Blog:www.sharepointblogs.com/ssa

Comments and Discussions

 
Questioninfection Pin
Member 27804808-Jun-12 5:25
Member 27804808-Jun-12 5:25 
QuestionWinsocks Pin
stixoffire6-May-12 21:41
stixoffire6-May-12 21:41 
Questionweb based application using HTTP protocol Pin
shridevi.kembhavi27-Mar-12 22:58
shridevi.kembhavi27-Mar-12 22:58 
QuestionPlease let me know how to connect to a server which requires user name and password for telnet login using winsock Pin
hansikaat24-Oct-11 21:08
hansikaat24-Oct-11 21:08 
QuestionHow to program Username Password Authentication using VB6 when login into a host using Winsock Pin
hansikaat24-Oct-11 20:27
hansikaat24-Oct-11 20:27 
GeneralMy vote of 5 Pin
(BlackBox) Ethical Hacker31-Oct-10 5:40
(BlackBox) Ethical Hacker31-Oct-10 5:40 
GeneralRe: My vote of 5 Pin
Ravi Sant4-May-11 23:43
Ravi Sant4-May-11 23:43 
Generalconcurrency Pin
jonny_lynch2-Feb-10 12:30
jonny_lynch2-Feb-10 12:30 
QuestionHow to Connect with Clint VB6 Cyber Cafe Management Project Pin
ankur_ap18-Jun-08 20:09
ankur_ap18-Jun-08 20:09 
GeneralTELNET UNIX SERVER USING VB Pin
sukh8430-Sep-06 10:26
sukh8430-Sep-06 10:26 
Questioncommunicating between VB app & Website Pin
siline18-Jan-06 16:10
siline18-Jan-06 16:10 
Generalhandling multiple clients using winsock array Pin
kalsoom ejaz19-May-05 11:34
susskalsoom ejaz19-May-05 11:34 
Generalhelp (idea for graduate procedure) Pin
Mohammed El.Giamal13-Aug-04 21:59
Mohammed El.Giamal13-Aug-04 21:59 
Generalsend Unicode font Pin
minhhien10-Apr-04 21:47
minhhien10-Apr-04 21:47 
Generalcopyright Pin
cchu20-Nov-03 5:06
cchu20-Nov-03 5:06 
GeneralRe: copyright Pin
Zap-Man10-Jul-10 4:07
Zap-Man10-Jul-10 4:07 
GeneralRe: copyright Pin
Ravi Sant4-May-11 23:43
Ravi Sant4-May-11 23:43 
Generalsend &amp;recv msg thru rs232 Pin
kutu120-May-03 4:02
kutu120-May-03 4:02 
GeneralRe: send &amp;recv msg thru rs232 Pin
Aleks7625-Feb-05 6:05
Aleks7625-Feb-05 6:05 
GeneralCoonecting Client/Server through ADSL Pin
AbidAli14-May-03 20:15
AbidAli14-May-03 20:15 
GeneralIs this example Multi-Thread Pin
nm0reira25-Mar-03 4:51
nm0reira25-Mar-03 4:51 
Questionwhat incase of proxy Pin
Manjit17-Feb-03 18:52
Manjit17-Feb-03 18:52 
GeneralHi, I have read your thread, and....a prb Pin
steve_cluj20-Jun-02 20:41
steve_cluj20-Jun-02 20:41 
Generalwinsock connect to unix Pin
tofeks7-Feb-02 16:10
tofeks7-Feb-02 16:10 
GeneralRe: winsock connect to unix Pin
S.S. Ahmed7-Feb-02 18:44
S.S. Ahmed7-Feb-02 18:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.