Library tutorials & articles

Client Server Programming with Winsock

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 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.

Comments

  1. 07 Jun 2005 at 05:28

    you can check your answers here hahahaa

  2. 03 Jun 2005 at 10:13

    i want to know how to transfer images that are in the picture1.picture box from a client to another picture1.picture to the server using winsock control, anyone could help me out in this matter, also try to mail me... if anyone has the solution,
    Pls how can i see answers to the already posted messeges cos i hv similar problem/questions as hav bn posted

  3. 04 Sep 2004 at 00:00

    i want to know how to transfer images that are in the picture1.picture box from a client to another picture1.picture to the server using winsock control, anyone could help me out in this matter, also try to mail me... if anyone has the solution,


    thanks

  4. 07 Jul 2004 at 05:05


    i want to transfere a file using C#
    either ftp or winsock
    if anyone knows how
    please help
    thank u

  5. 07 Jul 2004 at 05:05



  6. 28 Jan 2004 at 03:37

    you can use the and OCX that is available in the web www.j7tech.com.

  7. 28 Mar 2003 at 06:17

    when you use the winsock senddata method, the data gets stored in the outgoing winsock buffer. you have to wait until the buffer is completely sent. If you call the senddata method again then the data in the buffer gets overwritten by the new data. To prevent this you use the winsock sendcomplete method.


    For example:
    Private Sub subSendInfo
    ' ...
    '...
    ' pass the data to be sent to the winsock control
    winsock1.senddata(data)
    ' now the send complete will execute when the buffer is empty
    end sub



    Private Sub winsock1_SendComplete()
        ' buffer empty now send more data
                    call subSendInfo
    End Sub

  8. 16 Mar 2003 at 23:38

    how to sound transfer in winsock with the use of visual basic,,if any one have the answer then please send me the reply as soon as possible.send  reply on dthis maill address also. ======kuldip_infotech@yahoo.co.nz

  9. 19 Jan 2003 at 23:46

    how to send an image or a picture from the server to client using winsock?

  10. 02 Jan 2003 at 17:34

    Quote:
    [1]Posted by wmgoh on 5 Nov 2002 11:15 PM[/1]
    good day...


    i just want to ask how i can send files using winsock instead of using FTP in Internet Transfer Control?


    thanks

  11. 13 Dec 2002 at 02:36

    maybe if u uses commands like what i want to learn but i had some source on how to make all that but lost it and never found it again but use the predefined commands


    (in decloration or winsock.dataarive define each command)


    winsock1.dataarive
    if winsock1.dataarive then
    +stats+ = 100
    +name+ = name.text
    +workgroup+ = 98
    +ip+ = 0.0.0.0



    select case TCPdata


    case +name+       (notice i add a + in front and in back so that you can parish the data untill you get to + then use mid,right,left to get the data and store it into a string or something)


    case +stats+
    case +workgroup+
    case +ip+


    winsock1.senddata TCPdata




    if anyone knows how to do something like this please i beg of you to help me out and get me started.


    email=brianxmcd@aol.com
    aim=microsofs

  12. 13 Dec 2002 at 02:25


    i need help with making a winsock multi chat that uses a list of commands to do diffrent stuff like add nickname to the list of users connected then if they want there age displayed a command that sends there name and age but single commands not multiple commands at once and maybe add chatrooms stuff like that. anyone have a tutorial about how to do this?
    email = brianxmcd@aol.com aim = microsofs


    thanks

  13. 15 Nov 2002 at 16:32

    I too have this same problem...... but i found that on the microsoft website if you download service pack 4, there is a fix for this issue....BUT!!!!!! this resolution only works if you run the application using the computer that you downloaded the service pack for....which does absolutely no good for me...so if anyone knows how to fix this let me know....

  14. 11 Nov 2002 at 12:58

    i experienced the same problem:
    with several SendData one after another
    does't work
    i use DoEvents, but nothing
    i readed that this problem
    refers to the TCP/sliding window


    in which way can i solve that
    wiithout to use a "delay" between the sendDatas????

  15. 05 Nov 2002 at 23:15

    good day...


    i just want to ask how i can send files using winsock instead of using FTP in Internet Transfer Control?


    thanks

  16. 23 Oct 2002 at 13:50

    Quote:

    For i = 1 To iSockets
      Msgbox(*)
     Socket(i).SendData strOutData
    Next


    ohoh... use DoEvents


    Guido

  17. 11 Aug 2002 at 02:12

    I based on your program try to develop a chatroom.


    It is so strange that it cannot boradcast message in code like this:


    For i = 1 To iSockets  
       Socket(i).SendData strOutData
    Next
    (only the last Socket can get the message , i.e. Socket(iSocket))


    but can boradcast by this:
    For i = 1 To iSockets  
       Msgbox()
      Socket(i).SendData strOutData
    Next
    (
    = anything even empty)
    (only Msgbox can do so)


    Do you know what is the problem??


    Thxxx

  18. 22 Nov 2001 at 11:23

    its great but cani enable for for proxy on LAN?.

  19. 01 Jan 1999 at 00:00

    This thread is for discussions of Client Server Programming with Winsock.

Leave a comment

Sign in or Join us (it's free).