Library tutorials & articles

WinSock Control

Creating a Client

This is the basic code required to make a Server form, so now lets create a Client.

Add a new form, called frmClient, and add a WinSock control to the form, naming it tcpClient. Then, add the other controls listed below:

Control Name Control Type Caption/Text
txtSend TextBox  
txtRecieve TextBox  
txtPCName TextBox  
cmdSend CommandButton Send
cmdConnect CommandButton Connect

You will notice that this is exactly the same as the Server form, except for the cmdConnect button. There is less code required for the Client form, and is shown below:

Private Sub Form_Load()
    tcpClient.RemotePort = 100
    '// Get our Server Name, and set the form's caption
    Caption = "WinSock Tutorial - TCP Client @ " & tcpClient.LocalHostName
End Sub
Private Sub tcpClient_DataArrival(ByVal bytesTotal As Long)
    Dim strData As String
    tcpClient.GetData strData
    txtReceive.Text = strData
End Sub
Private Sub cmdSend_Click()
    '// send the data
    tcpClient.SendData txtSend.Text
End Sub
Private Sub cmdConnect_Click()
    '// connect
    tcpClient.RemoteHost = txtPCName.Text '// Change this to the name of the PC
    tcpClient.Connect
End Sub

The Form_Load procedure sets the RemotePort properties. The RemotePort property is the port that the server is watching. In the code for the Server form, we set this to 100.

The next procedure is the same as in the Server form, with only the name of the WinSock control changed. This fills txtReceive with the data that has arrived.

The cmdSend_Click() procedure sends the data contained in txtSend, and the cmdConnect_Click() procedure attempts to connect to the PC which is entered in txtPCName. The Server form must already be open on this PC for this to work!

Finally, we will create another simple form, called frmStartup, with two command buttons (cmdServer and cmdClient). This will simply let you open which forms you want. The code you need is below:

Private Sub cmdServer_Click()
    frmServer.Show
End Sub

Private Sub cmdClient_Click()
    frmClient.Show
End Sub

Don't forget to change the start up form to frmStartup. To do this, click Project|Properties, and select frmStartup as the Startup Object

Comments

  1. 20 Feb 2008 at 01:22

    Make sure that you have a reference to the winsock ocx, and a winsock control in the project and verify that its called tcpClient (you can prob add a line like Dim tcpClient as New mswinsck to load the control at runtime but my vb is a bit rusty so i dont know if that line is 100% correct sorry)

  2. 13 Feb 2008 at 06:37

    Hello, I was reading the "WinSock Control - Creating a Server" article
    I followed it exactly the way it was done on the page.

    I get the following error when testing my app though...
    Run-time error '424':

    Object required




    When I click debug, this is the string that i get the error on:
    Private Sub Form_Load()
        tcpClient.RemotePort = 100           /////////*error line*//////////////
        '// Get our Server Name, and set the form's caption
        Caption = "prayog " & tcpClient.LocalHostName
    End Sub

    any ideas ,plz reply

  3. 15 Oct 2007 at 10:02

    akumar, you don't simply copy the EXE file on to other system. Use Package and Deployment wizard to make setup file so that it includes the winsock.ocx and other neccessary files. So that where ever you install your program will work. - Ramesh

  4. 04 Aug 2007 at 10:35

    How to distribute MSwinsock.ocx along with the programm. The client and Server is working in my pc. But when I executed the exe file in another pc its giving me error.

    Can u please guide.

  5. 16 May 2007 at 06:53

    you would either have to relay the message via the server -

    ie client sends message >>>>> server >>>> server forwards to other client

    or you would have to establish a connection between the 2 clients - either way you would probably have to relay some information to the other client(ie connection details) via the server

    the 1st option would be fine if you're sending small amounts of information - ie text for a im program, but the 2nd option would probably be a lot more efficient and reliable for sending large files as it skips a hop.

    the 2nd option could get complicated - in the case of computers being behind router/firewalls and setting up port forwarding on each client in order to accept a connections - maybe someone knows a way around this???

    wheras the 1st option only requires a port opened/forwarded on the router/firewall that connects the server to the internet

    Anyways hopefully that gives you a few ideas - also the 2nd option is probably better if you intend to use the program over lan only or if you need to transfer large amounts of data.

  6. 15 Aug 2006 at 09:36

    When I should use WinSock control method Bind() ?

    Can I in some way to listen on port 80 when for example Apache server is listening on this port without Winsock control to return error "Address in Use"

     

     

  7. 23 Jul 2006 at 11:26

    thanks for this tutoril, it's really helped, but can anyone please explain to me how to enable to two clients to be able to communicate with each other, because so far all i can do is communicate between the client and server. Would each window have to be a server for this to work? thanks in advance.

  8. 03 Aug 2005 at 22:41

    Beware of some bugs in the Winsock control.  Keep in mind that all protocols have limitations.  This information is from Microsoft Press - Network Programming for Microsoft Windows.


    The first bug is relatively minor and deals with dynamically loading and unloading the control. A memory leak is incurred when unloading a previously loaded control. This is why we don't load and unload the controls as clients connect and disconnect in our server example. Once the control is loaded in memory, we leave it for possible use by other clients.


    The second bug involves closing a socket connection before all data queued is sent on the wire. In some cases, calling the Close method after the SendData event (when Close is processed before SendData) causes data to be lost, at least from the receiver's point of view. You can get around this problem by catching the SendComplete event (which is triggered when SendData has finished putting the data on the wire). Alternatively, you could arrange the send/receive transactions so that the receiver issues the Close command first, when it has received all the data expected. This would then trigger the Close event on the sender, which would then signal that all the data sent has been received, and that it's now OK to shut down the connection completely.


    The last and most severe bug is the dropping of data when a large buffer is submitted for transfer. If a large enough block of data is queued up for network transmission, the control's internal buffers get messed up and some data is dropped. Unfortunately, there is no completely perfect workaround for this problem. The best method is to submit data in chunks less than 1000 bytes. Once a buffer is submitted, wait for the SendComplete event to fire before submitting the next buffer. This is a pain, but it's still the best way to make the control as reliable as possible.


    From my experience, you can overflow the buffer on the receiving machine even if you trap the SendComplete event.  I believe the event fires after the send buffer is cleared, but if you immediately send more data then there is no guarantee that the receiving machine will have taken that data and used it before reading the next buffer.  I still lose (large) chunks of data on slow aircard connections.  I may follow up in the future as I Endeavour to complete my mission-critical application.  If sending more data than the buffer can handle, I suggest handshaking the messages.  Use a stop character to end each message sent.  When this stop character is received, send a message back to the sender saying, “yes, I received a message.”

  9. 15 Oct 2004 at 18:56

    Hello everybody!!!.


    Can i use winsock conection with a dial-up. I mean i want to call to a Computera A via modem Computer B answer the call, the whole process handle with winsock. Can i do this??


    Please i need this information.........


    If i connot do it this way, how can i do it??


    Thanks.

  10. 07 Oct 2004 at 20:13

    Currently, I am try to establish connection between the server and client under one PC. I have use the exact coding from the Winsock Control webpage.
     When i try to run the Startup form, i having some error message. The error mesage show like this:


      - As i type the PC Name of the Server in the Client Form, it comes with Run Time Error '40020': Invalid Operation at Current State
      - If i type a message in the Server Form and try to send, a Window Propmt comes with a statement like "You must connected to the client first.
     
      I really need some help for the problem above.

  11. 02 Jun 2004 at 07:03

    I think, You must have real IP address of the server process. if you communicate with the server application using client. and you are using proxy then the server application should be executed on the machine which has real IP.


    Your client application need not be have real IP it will directly connected with the server appliation and once the connection is established by the client then u are free to communicate.

  12. 16 May 2004 at 14:35

    psycho_sarge,
       I believe that that code shuts down a remote computer

  13. 28 Apr 2004 at 02:16

    Hey
    To all of u.
    I connect to internet using proxies so what is the process to connect my vb applications using winsock to connect to internet. Many toturials on winsock describing the client server app. I want to know how i connect to internet using winsock in my app's + how to handle proxies in winsock control + my LAN administrator server also need authentication how this can be done using winsock to automatically log userid and password.
    All Comments and Resources gives high regards.

  14. 05 Feb 2004 at 11:29

    WHAT DOES THIS DO?


    Private Sub Form_Load()
    TxtPort.Text = Winsock1.LocalPort
    If TxtPort.Text = "0" Then
    TxtPort.Text = "10101"
    End If
    Winsock1.LocalPort = TxtPort.Text


    txtIP.Text = Winsock1.LocalIP
    Winsock1.Listen
    End Sub


    Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
    Dim strCommand As String


    Winsock1.GetData strCommand


    If txtCommand.Text = "SHUT DOWN" Then
    AdjustToken
    ExitWindowsEx (EWXSHUTDOWN Or EWXFORCE Or EWX_REBOOT), &HFFFF
    End If


    Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long)
    Winsock1.Close
    Winsock1.Accept requestID
    End Sub



    Private Sub cmdShutdown_Click()
    Dim strCommand As String
    txtCommand.Text = "SHUT DOWN"


    strCommand = txtCommand.Text
    wnsCommand.SendData strCommand
    DoEvents
    End Sub



    Private Sub cmdConnect_Click()
    wnsCommand.RemoteHost = txtIP.Text
    wnsCommand.RemotePort = TxtPort.Text
    wnsCommand.Connect


    cmdConnect.Visible = False
    cmdDisconnect.Visible = True
    End Sub


    Private Sub cmdDisconnect_Click()
    wnsCommand.Close
    cmdConnect.Visible = True
    cmdDisconnect.Visible = False
    End Sub


    Module
         Option Explicit


         Public Type LUID
            UsedPart As Long
            IgnoredForNowHigh32BitPart As Long
         End Type


         Public Type TOKEN_PRIVILEGES
            PrivilegeCount As Long
            TheLuid As LUID
            Attributes As Long
         End Type


         Const EWXSHUTDOWN As Long = 1
         Const EWX
    FORCE As Long = 4
         Const EWXREBOOT = 2
       
       End Sub
       
         Declare Function GetCurrentProcess Lib "kernel32" () As Long
         Declare Function OpenProcessToken Lib "advapi32" ( _
            ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, _
            TokenHandle As Long) As Long
         Public Declare Function LookupPrivilegeValue Lib "advapi32" _
            Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, _
            ByVal lpName As String, lpLuid As LUID) As Long
         Public Declare Function AdjustTokenPrivileges Lib "advapi32" ( _
            ByVal TokenHandle As Long, ByVal DisableAllPrivileges As Long, _
            NewState As TOKEN
    PRIVILEGES, ByVal BufferLength As Long, _
            PreviousState As TOKEN_PRIVILEGES, ReturnLength As Long) As Long


         Public Sub AdjustToken()


            Const TOKENADJUSTPRIVILEGES = &H20
            Const TOKENQUERY = &H8
            Const SE
    PRIVILEGEENABLED = &H2
            Dim hdlProcessHandle As Long
            Dim hdlTokenHandle As Long
            Dim tmpLuid As LUID
            Dim tkp As TOKEN
    PRIVILEGES
            Dim tkpNewButIgnored As TOKEN_PRIVILEGES
            Dim lBufferNeeded As Long


            hdlProcessHandle = GetCurrentProcess()
            OpenProcessToken hdlProcessHandle, (TOKENADJUSTPRIVILEGES Or _
               TOKEN_QUERY), hdlTokenHandle


            LookupPrivilegeValue "", "SeShutdownPrivilege", tmpLuid


            tkp.PrivilegeCount = 1
            tkp.TheLuid = tmpLuid
            tkp.Attributes = SEPRIVILEGEENABLED


            AdjustTokenPrivileges hdlTokenHandle, False, tkp, _
               Len(tkpNewButIgnored), tkpNewButIgnored, lBufferNeeded


         End Sub

  15. 01 Dec 2003 at 12:22

    ok, this is simple explanation and code.
    what is does is basically have a main winsock control that is listening on port x from the beginning (this can have index 0 and be created a design-time)

    Code:
    Winsock(0).LocalPort = x
    Winsock(0).Listen

    and when there is a connection request:
    Code:
    Private Sub Winsock_ConnectionRequest(Index As Integer, requestID As Long)
    If Index = 0 Then
       Dim NewIndex As Integer
       
       NewIndex = UBound(Winsock) + 1
       Load Winsock(NewIndex)
       Winsock(NewIndex).Accept requestID
    End If
    End Sub

    and that's all the code. when there's an error, you want to display it and then close that winsock, or in the listening winsock case, you want to start listening again. you don't have to have the listening winsock as index 0 - it can have any name.

  16. 01 Dec 2003 at 10:15

    Sorry,
    As I haven't programmed with VB a while, I am not able to help you. Hovewer, when putting all this code together that is posted here you should get it all right, like I did. I can also give theoretical information as I don't even remember the syntax of VB, and might 80% give wrong code. If you have decent knowledge of the structure of VB you should be able to do it.


    Again, sorry... No offence

  17. 01 Dec 2003 at 10:06

    People
    Like myself are only viewing this when someone has bumped the topic... me myself, id love to know how to get it working... but not if its gonna cause offence

  18. 01 Dec 2003 at 09:56

    And can't believe this either that after 2 years people are still ACTIVELY monitoring this topic. lmfao

    Quote:

    Dan Forever said:
    before you said the code above doesn't work, could you tell me how you fixed that or at least give me some tips / pointers?

    How can anybody help you to get it working when that person him/herself didn't get it working?

  19. 01 Dec 2003 at 09:44

    hehe

  20. 01 Dec 2003 at 09:37

    WOW! Look at the time of the original comment! Now I have returned, with a different nick (damn missing password generator! ) and still after years people are puzzled with it


    Man, it was so long ago I even don't remember the solution. lol. Maybe a little... Well, here's your answer: do a google on how to use control arrays in VB. Just create a control array of sockets and when an incoming connection event is triggered, create a new socket in the array and let IT accept the connection, rather than letting the LISTENER to accept the connection (making it abandon it's listening state and switch to connected state)


  21. 17 Nov 2003 at 13:57

    Call me a dufus but i cant get this working - I think im having trouble understanding the control array aspect of it


    If someone could provide a VERY simple example in full... I would be very grateful

  22. 17 Nov 2003 at 13:50

    I would also appreciate the info on how to xfer files but that code is very... extensive


    is there a simpler way or an explanation

  23. 04 Sep 2003 at 19:51

    I think if another program is using that port, your program will crash, or not get a reply. I suggest you open mIRC, then have your program connect on port 6667 (the port mIRC uses) and see what happens. If it crashes, you can use an error handler to make it try another port instead. If it just doesn't connect, have it try a few more ports before giving up. The program on the other end should be listening on all the ports that may be used, and when a connection is established stop listening on every port except the one it's connected on.

  24. 04 Sep 2003 at 14:38

    Hello, I had wrote a program in VB 6.0 and I had tested it width the
    server and the client in the same computer and tree more clients in others
    computers, by now the program works fine, but I do not if it is correct
    to ask to the client for the port it is using to listen because I do not who to reserv
    a port for my application program only. The only fixed port is the server
    listen port. How can I do to be sure than another applications do not use
    the same port my application is using. Me applications is a real time program to
    get data from the factory process and to advise the factory operator about
    problems in the process. It works well but the other day another programmer
    was testend a application and it has using the same port than my application
    and it stops with the "error port is in use".


    Please, excuse my poor English

  25. 30 Aug 2003 at 13:17

    Quote:
    [1]Posted by beezm on 24 May 2003 12:31 AM[/1]


    Hello, I was reading the "WinSock Control - Creating a Server" article
    I followed it exactly the way it was done on the page.


    I get the following error when testing my app though...
    Run-time error '424':


    Object required





    When I click debug, this is the string that i get the error on:


    Private Sub tcpServer_DataArrival(ByVal bytesTotal As Long)
       Dim strData As String
       tcpServer.GetData strData
       txtreceive.Text = strData
    End Sub


    on the txtreceive.Text = strData string I get the error.


    Any ideas?



    I know exactly what is wrong because I had the same problem. This article has a minor spelling mistake. In the first part of the server, when it tells you the names to name the controls, it says txtRecieve, with an 'ie'. However, in the code, it uses txtReceive. Change the control's name to 'ei' instead of 'ie', and it will work like a charm.

  26. 25 Aug 2003 at 08:17

    I only speak a lite bit of english


    I would like to now the name of the file in Windows to define a new
    LocalPort (UDP port)


    thanks Javier

  27. 11 Jul 2003 at 11:14

    Yes you're right... but in my case... when my VB.NET application have to connect to the vbce application which is working with winsock control, i think i have to use winsock control.
    And actually, i can connect, and i can send data without any problems from VB.NET to VB(winsock). But the problem is when i'm trying use:


    Private Sub TcpServerPDA1DataArrival(ByVal sender As Object, ByVal e As AxMSWinsockLib.DMSWinsockControlEventsDataArrivalEvent) Handles TcpServerPDA1.DataArrival
                  dim string
                  tcpserver.getdata(string)
                  msgbox(string)
    end sub


    is not working... is not even showing the msgbox! Is just leaving procedure.
    So can anybody tell me... how to read packets in VB.NET which are sended from VB (winsock control)??

  28. 03 Jun 2003 at 11:41

    'Heres the download module I'm using for my gnutella client
    'You should be able to make it out from this.
    ' I can post the upload module if you wish


    'Basic download routines like receiving data, storing etc


    'Dim DLBytePosition&(0 To 32767)'can store a byte position for every
                                   'winsock thread ;)
                                   'for later use


    'ToDo: Set LocalFile$, filter / create HTTP header


    Public Function InitDownload%(WinsockIndex%, LocalFile$, Size)
           'this function returns the file number of the opened file
           'or -1 if the initialization failed.
           '(e.g. invalid filename, file already open, disk full,etc)


           On Local Error GoTo InitDownloadError
           FFILE% = FreeFile 'find a new file number for open


           Open LocalFile$ For Binary As #FFILE%
           'this command openes the file and holds it open until
           'close #FFILE% or until programm closed


           'Now the file is opened and ready for our dataArrivals
           InitDownload% = FFILE%
           'Doing some additional work
           File = Mid(LocalFile, InStrRev(LocalFile, "\") + 1, Len(LocalFile))
           If downloadmessage(WinsockIndex%).fileindex = 0 Then
               downloadmessage(WinsockIndex%).fileindex = addtodownloads(File, "Downloading", 0, Size, 0)
           End If
           Exit Function


    InitDownloadError: InitDownload% = -1
    End Function
    Public Sub RebuildBroken()
       Set objTS = objFS.OpenTextFile(App.Path & "/broken.net", ForReading)
       While Not objTS.AtEndOfStream
           Temp = objTS.ReadLine
           Temp = Split(Temp, "|")
           
           downloadmessage(Int(Temp(7))).fileindex = addtodownloads(Temp(0), "Connecting", Temp(1), Temp(2), "0")
           Call OpenFileTransfer(Int(Temp(6)), CStr(Temp(0)), Temp(3), Temp(4), Temp(1), Temp(2), Int(Temp(7)))
       Wend
    End Sub
    Public Function StoreData&(Filenum%, DataString$)
           'This function is for storing incoming Data into a
           'download file
           'it returns -1 when storage failed, or the new file size(bytes)
           'when success.


           On Local Error GoTo StoreDataError
           
           Seek #Filenum%, LOF(Filenum%) + 1 'point to next byte(for writing)
           
           Put #Filenum%, , DataString$ 'write data
           
           StoreData& = LOF(Filenum%) 'new file length
           'MsgBox StoreData
           Exit Function
           
    StoreDataError: StoreData& = -1
    End Function


    Public Function CloseDownload%(Filenum%)
           'This function closes the file, socket,remove from listbox etc (TODO)
           On Local Error GoTo CloseDownloadError


           Close #Filenum%
           downloadmessage(Index).filerunning = False
           Exit Function
           
    CloseDownloadError: CloseDownload% = -1
    End Function
    'Coded by Guo Xu
    'Opening FileTransfer. Opens new socket and sends the request after connect
    'Creates a new array using the type strdownloaddata to store the needed
    'information.


    Public Sub OpenFileTransfer(FileIndex As Integer, FileName As String, ip, port, StartRange, Filesize, Optional DLIndex As Integer)
       packet = "GET /get/" & FileIndex & "/" & FileName & " HTTP/1.1" & vbCrLf
       packet = packet & "User-Agent: " & Version & vbCrLf
       packet = packet & "Host: " & ip & ":" & port & vbCrLf
       packet = packet & "Connection: Keep-Alive" & vbCrLf


       If StartRange = 0 Then
           packet = packet & "Range: bytes=0-" & vbCrLf & vbCrLf
       Else
           packet = packet & "Range: bytes=" & StartRange & "-" & vbCrLf & vbCrLf
       End If
       'MsgBox packet
       For i = 1 To frmMain.DownloadSock.UBound
           If StartRange = 0 Then
           If frmMain.DownloadSock(i).state = 0 Then
           'MsgBox i
               If downloadmessage(i).filenumber = 0 Then
                   frmMain.DownloadSock(i).Connect ip, port
                   downloadmessage(i).filemessage = packet
                   downloadmessage(i).filename = FileName
                   downloadmessage(i).filesize = Filesize
                   downloadmessage(i).fileremoteindex = FileIndex
                   download
    message(i).fileip = ip
                   download
    message(i).fileport = port
                   Call Msg("Requesting file. On DLSocket " & i)
                   Exit For
               End If
           End If
           Else
           If frmMain.DownloadSock(DLIndex).state = 0 Then
               If DLIndex <> 0 Then
                   frmMain.DownloadSock(DLIndex).Connect ip, port
                   download
    message(DLIndex).filecurrentsize = StartRange
                   downloadmessage(DLIndex).filemessage = packet
                   downloadmessage(DLIndex).filename = FileName
                   downloadmessage(DLIndex).filesize = Filesize
                   downloadmessage(DLIndex).filerunning = True
                   downloadmessage(DLIndex).fileremoteindex = FileIndex
                   download
    message(DLIndex).fileip = ip
                   download
    message(DLIndex).file_port = port
                   
                   Call Msg("Requesting file. On DLSocket " & DLIndex)
                   Exit For
               End If
           End If
           End If
       Next
    &nb

  29. 03 Jun 2003 at 11:40

    'Heres the download module I'm using for my gnutella client
    'You should be able to get the idea from this - if you wish I can post the upload module
    'Basic download routines like receiving data, storing etc




    'Dim DLBytePosition&(0 To 32767)'can store a byte position for every
                                   'winsock thread ;)
                                   'for later use


    'ToDo: Set LocalFile$, filter / create HTTP header


    Public Function InitDownload%(WinsockIndex%, LocalFile$, Size)
           'this function returns the file number of the opened file
           'or -1 if the initialization failed.
           '(e.g. invalid filename, file already open, disk full,etc)


           On Local Error GoTo InitDownloadError
           FFILE% = FreeFile 'find a new file number for open


           Open LocalFile$ For Binary As #FFILE%
           'this command openes the file and holds it open until
           'close #FFILE% or until programm closed


           'Now the file is opened and ready for our dataArrivals
           InitDownload% = FFILE%
           'Doing some additional work
           File = Mid(LocalFile, InStrRev(LocalFile, "\") + 1, Len(LocalFile))
           If downloadmessage(WinsockIndex%).fileindex = 0 Then
               downloadmessage(WinsockIndex%).fileindex = addtodownloads(File, "Downloading", 0, Size, 0)
           End If
           Exit Function


    InitDownloadError: InitDownload% = -1
    End Function
    Public Sub RebuildBroken()
       Set objTS = objFS.OpenTextFile(App.Path & "/broken.net", ForReading)
       While Not objTS.AtEndOfStream
           Temp = objTS.ReadLine
           Temp = Split(Temp, "|")
           
           downloadmessage(Int(Temp(7))).fileindex = addtodownloads(Temp(0), "Connecting", Temp(1), Temp(2), "0")
           Call OpenFileTransfer(Int(Temp(6)), CStr(Temp(0)), Temp(3), Temp(4), Temp(1), Temp(2), Int(Temp(7)))
       Wend
    End Sub
    Public Function StoreData&(Filenum%, DataString$)
           'This function is for storing incoming Data into a
           'download file
           'it returns -1 when storage failed, or the new file size(bytes)
           'when success.


           On Local Error GoTo StoreDataError
           
           Seek #Filenum%, LOF(Filenum%) + 1 'point to next byte(for writing)
           
           Put #Filenum%, , DataString$ 'write data
           
           StoreData& = LOF(Filenum%) 'new file length
           'MsgBox StoreData
           Exit Function
           
    StoreDataError: StoreData& = -1
    End Function


    Public Function CloseDownload%(Filenum%)
           'This function closes the file, socket,remove from listbox etc (TODO)
           On Local Error GoTo CloseDownloadError


           Close #Filenum%
           downloadmessage(Index).filerunning = False
           Exit Function
           
    CloseDownloadError: CloseDownload% = -1
    End Function
    'Coded by Guo Xu
    'Opening FileTransfer. Opens new socket and sends the request after connect
    'Creates a new array using the type strdownloaddata to store the needed
    'information.


    Public Sub OpenFileTransfer(FileIndex As Integer, FileName As String, ip, port, StartRange, Filesize, Optional DLIndex As Integer)
       packet = "GET /get/" & FileIndex & "/" & FileName & " HTTP/1.1" & vbCrLf
       packet = packet & "User-Agent: " & Version & vbCrLf
       packet = packet & "Host: " & ip & ":" & port & vbCrLf
       packet = packet & "Connection: Keep-Alive" & vbCrLf


       If StartRange = 0 Then
           packet = packet & "Range: bytes=0-" & vbCrLf & vbCrLf
       Else
           packet = packet & "Range: bytes=" & StartRange & "-" & vbCrLf & vbCrLf
       End If
       'MsgBox packet
       For i = 1 To frmMain.DownloadSock.UBound
           If StartRange = 0 Then
           If frmMain.DownloadSock(i).state = 0 Then
           'MsgBox i
               If downloadmessage(i).filenumber = 0 Then
                   frmMain.DownloadSock(i).Connect ip, port
                   downloadmessage(i).filemessage = packet
                   downloadmessage(i).filename = FileName
                   downloadmessage(i).filesize = Filesize
                   downloadmessage(i).fileremoteindex = FileIndex
                   download
    message(i).fileip = ip
                   download
    message(i).fileport = port
                   Call Msg("Requesting file. On DLSocket " & i)
                   Exit For
               End If
           End If
           Else
           If frmMain.DownloadSock(DLIndex).state = 0 Then
               If DLIndex <> 0 Then
                   frmMain.DownloadSock(DLIndex).Connect ip, port
                   download
    message(DLIndex).filecurrentsize = StartRange
                   downloadmessage(DLIndex).filemessage = packet
                   downloadmessage(DLIndex).filename = FileName
                   downloadmessage(DLIndex).filesize = Filesize
                   downloadmessage(DLIndex).filerunning = True
                   downloadmessage(DLIndex).fileremoteindex = FileIndex
                   download
    message(DLIndex).fileip = ip
                   download
    message(DLIndex).file_port = port
                   
                   Call Msg("Requesting file. On DLSocket " & DLIndex)
                   Exit For
               End If
           End If
           End If
       Next
    &n

  30. 24 May 2003 at 00:31



    Hello, I was reading the "WinSock Control - Creating a Server" article
    I followed it exactly the way it was done on the page.


    I get the following error when testing my app though...
    Run-time error '424':


    Object required





    When I click debug, this is the string that i get the error on:


    Private Sub tcpServer_DataArrival(ByVal bytesTotal As Long)
       Dim strData As String
       tcpServer.GetData strData
       txtreceive.Text = strData
    End Sub


    on the txtreceive.Text = strData string I get the error.


    Any ideas?

  31. 20 Apr 2003 at 21:24

    How do I get this to work with a RichTextBox, I've tried, but nothing gets entered into the recieve box

  32. 12 Apr 2003 at 04:20

    you would probably want to create a sub that enables and disables all
    buttons on your form something like:


    Private Sub ButtonState(Msg As Boolean)
    If Msg Then
      Disable/Enable your command Buttons
    Else
      Enable/Disable you command Buttons
    End If
    End Sub


    in your timer


    If Winsock1.State <> SckConnected Then ' if not connected
    Call ButtonState(False) ' Disable Buttons
    Winsock1.Connect "host", Port ' Reconect
    Do While Winsock1.State <> SckConnected 'loop while connection is commencing
    DoEvents ' give control back to user
    Loop
    ' when you get here your winsock has made a new connection
    Call Buttonstate(True) ' Enable Buttons
    End If


    Lee, VbExplorer

  33. 03 Jan 2003 at 18:21

    VB.NET has made significant changes to the way these things work, and basically you shouldn't use the WinSock control in .net.... take a look at the System.Net and System.Net.Sockets namespaces instead.

  34. 03 Jan 2003 at 16:04

    I know how to connect and all of that, but I need to know how to transfer files. All the places I looked on the web want me to convert to binary first, which makes sense, but im not exactly sure how  can someone please give me some feedback on this, thanks

  35. 03 Jan 2003 at 15:59

    I had the same problem as you dude. I can do all the chats and multi-connects in VB6, but when I try and do it in VB.net, it wont work at all. It has all these errors and stuff, and it wont let me type what I want. I will always change it by adding or taking away brackets and quotations. I have no idea whats wrong with it, or if you just have to learn new code to get around it

  36. 03 Jan 2003 at 15:56

    This is a great site I learned all the basics about the Winsock Conrtol, it doesnt skip out on anything. When you are doing good with the basics, it has some more complicated stuff like mulit-connects and stuff


    http://www.winsockvb.com

  37. 03 Jan 2003 at 15:49

    Take out the If..Then Statement. The index might change, so it might not count, try this


    'This goes in the Winsock_ConnectionRequest Part


    chatConnect = chatConnect + 1
    load winsock(chatConnect)
    Winsock(chatConnect).Accept RequestId


    Hope THis works!

  38. 03 Jan 2003 at 15:38

    All you have to do is make a label that tells you if you are connected or not. on the "winsock_connect" part, put it so that when it does connect, the caption says "connected". Then you can use a Timer(set for 500 or something) and an If..Then Statement like this


    'This goes in the Winsock1_Connect Part
    Label1.Caption = "Connected"



    ' This goes in the Timer Control
    If Label1.Caption = "Connected" Then
    Winsock1.Connect "host-goes-here", port#here
    End If
    ' End Code


    I have made simalar program that did this, I didnt want to have to connect them all the time, so I made it do it automaticly, hope this is some help!

  39. 30 Dec 2002 at 01:34

    hi,
      What should i do if in a client server model , client is under proxy...how will client connect to server
    Anwar

  40. 13 Dec 2002 at 03:11

    ok i think u dled vb (just vb) and you didnt dled MVS (microsoft visual studios).

  41. 09 Dec 2002 at 20:45

    What version are you all using for this program?  I am using VB.NET Professional, and I don't think everything is the same.  Let me know... Thanks.

  42. 31 Oct 2002 at 08:35

    can any one teach me how to make my client form Automaticly connect
    to the server if ever it was disconnected...


  43. 09 Oct 2002 at 11:59

    To the person who wanted to know about multiple connections to a single Winsock application, check out: http://flash.lakeheadu.ca/~bmisner/lustuff/yearthree/eng3553/labs/vbandwinsock.pdf


    In short, you keep creating multiple instances of your Winsock control using the "Load" function as more connection requests come in.


    As for not finding the Winsock control in your list of modules, try going to the Project menu -> Components and then scrolling down to "Microsoft Winsock Control 6.0 (SP5)". Check the checkbox to the left of that entry, and the Winsock control should show up in your controls palette on the left hand side of your screen (the Winsock control icon looks like two computers with a small red arrow curving between them).


    Hope that was helpful!


    Bill
    billin@jadeforest.com

  44. 29 Aug 2002 at 08:52

    Private Sub Form_Load()
      Dim Outputstring As String
      Outputstring = "some text"
       
    '  set receivig side
      Winsock1.Bind 8526                 ' portnumber < 65536



    '  set sending side
    '  Winsock2.RemoteHost = "127.0.0.1"  ' remote side ip in form "x.x.x.x"
      Winsock2.RemoteHost = "localhost"
      Winsock2.LocalPort = 65535         ' portnumber < 65536
      Winsock2.RemotePort = 8526         ' we send data to winsock1 listening port


     
      Winsock2.SendData (Outputstring)
    End Sub


    Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
      Dim Inputstring As String
      Winsock1.GetData Inputstring
      Debug.Print Inputstring
    End Sub

  45. 18 Aug 2002 at 13:59

    Hi all,


    I use winsock to transfer some files beetwin 2 PCs. my program work fine, but the transfer speed is slow.
    Is there something to set the transfer speed?


    thx.


    Cláudio

  46. 11 Aug 2002 at 14:57

     The tutorial is great for beginners! But... you forgotten one important thing: how to connect more than one client to a server! This is really important! It is really simple, but vital!

  47. 31 Jul 2002 at 15:42

    I think it would help quite much if you told us where it went wrong and what the compiler has to say about it.

  48. 31 Jul 2002 at 15:40

    This tutorial really is great.
    As for that matter of fact, it's probably the very best tutorial about winsock programming I've ever read.


    However, it only concentrates on TCP connections.
    Does anyone have any idea where I would find a tutorial about UDP connections, using winsock?

  49. 10 Jul 2002 at 14:16

    Sussed it, it was not a dumb instal program, it was a dumb me that did not select ActiveX components when i installed VB!!!!!


    Dumb dumb dumb, i know!!


    Thanks anyway

  50. 09 Jul 2002 at 20:05

    wierd!


    Prolly some dumm ass program has uninstalled it? Try re-running SP5 setup to see if it will re-install it(may not) otherwise download it from the web and register it.


    Are you sure u cant see it in the list?

  51. 09 Jul 2002 at 18:48

    Having trouble with any winsock stuff,


    can anyone help


    I cannot find the winsock control, I am running VB6 with SP5 on XP and i have tried to find it in the list of controls but it is not there!!


    Anyone got any ideas??


    thanks guys & girls!!

  52. 25 Jun 2002 at 03:34

    I have follow your step. but it still cannot work.

  53. 18 Jun 2002 at 23:18

    I try to link the page but nothing inside

  54. 10 May 2002 at 19:20

    lol@james! Yeah right!  

  55. 10 May 2002 at 16:02

    there is a basic example @ http://www.developerfusion.com/show/193/

  56. 10 May 2002 at 16:01

    there is a basic example @ http://www.developerfusion.com/show/193/

  57. 10 May 2002 at 16:00

    I never made the claim that it was scalable  ... it's only supposed to be an introduction to the control. Since when does VB support multithreading anyway? (and since when was VB/the winsock control scalable...??)


  58. 03 May 2002 at 14:33

    Great exercise, worked first time, and i think i know whats going on, I shall attempt to get it working on the original task i had in mind, I shall report back!

  59. 08 Apr 2002 at 11:52

    before you said the code above doesn't work, could you tell me how you fixed that or at least give me some tips / pointers?

  60. 07 Apr 2002 at 11:15

    Private Sub wnskChat_ConnectionRequest(Index As Integer, ByVal requestID As Long)


    I get a wierd error about not recognising that, but it works without the index as int.


    would wnskChat_DataArrival(blah blah) work for every wnskChat in a control array?

  61. 07 Apr 2002 at 07:37

    u wanna see the code, nah sorry i dont give out code, and especially in beta's. far too buggy, if u wanna see the exe at the moment then i attached a zip file, the exe and pic must be in the same directory, any probs let me know.


    chad

  62. 07 Apr 2002 at 07:33

    would I be able to see the code for recieving data? and what version of vb are you using?

  63. 06 Apr 2002 at 21:00

    yeah i got a working example of a multi user chat prgram im working on (since school banned msn), the chat feature works, but im still in the beta stages adding features an trying to fix any bugz that exist.


    chad

  64. 06 Apr 2002 at 13:37

    Does anyone have an example of this working?
    I'm currently trying to get to network a game I made with a friend that works in 'hotseat' mode, but recieving info from clients seems to present a problem. mainly because changing anything at all in the datarecieved sub means VB6 says "I don't recognise this" - adding index as integer, and you can't stick the index number in after the name cos it confuses it with the variables that would be in the backets at the end of a sub

  65. 02 Apr 2002 at 11:09

    How to send file for example mp3, pic, etc by using winchock?

  66. 01 Apr 2002 at 07:56

    It might be worth taking a look at the SocketWrench control...


    NetGert: there are numerous C++ compilers available... Take a look at some of the websites listed at http://www.developerfusion.com/c/

  67. 01 Apr 2002 at 07:43

    Do they use C++? I've heard a lot of good about that. If anyone works with C++, please give me the URL where I can download that.


    Code:
    #include windows.h



  68. 29 Mar 2002 at 00:12

    LOL

  69. 29 Mar 2002 at 00:09

    After searching the internet for hours I've finally found something that works.  Being a complete beginner at winsock vb, this tutorial is a superb starting point.  Thank you.

  70. 05 Mar 2002 at 10:09

    But what are they then using? Delphi?

  71. 04 Mar 2002 at 03:03

    How to send file for example mp3, pic, etc by using winchock

  72. 04 Mar 2002 at 01:42

    hello, im starting to experiment with vb see what i can do, has anyone done an example of a winsock chat that can allow more than one client? when i tried the code i still got the same errors. If anyone can help me out my email addy is chad_leverington@hotmail.com


    thanks in advance
    chad

  73. 28 Feb 2002 at 14:29

    NetGert: there is no mystery. The difference is they don't use Visual Basic to write their programs

  74. 28 Feb 2002 at 13:04

    You need to set up a control Array. The first Array (0) should be the listening Socket. On its Connection Request Have it load a new Object. Since the connection was already accepted you don't need to set the port so assign it to 0.The code looks like this:
    Private Sub wnskChat_ConnectionRequest(Index As Integer, ByVal requestID As Long)
    If Index = 0 Then
    intMax = intMax + 1
    Load wnskChat(intMax)
    wnskChat(intMax).LocalPort = 0
    wnskChat(intMax).Accept requestID
    End If
    End Sub


    Good Luck!

  75. 27 Feb 2002 at 02:09

    Quote:
    [1]Posted by NetGert on 30 Oct 2001 10:23 AM[/1]
    How to connect to multiple clients? Like Chats do? If I want to connect another client to server, it won't connect, it gives an error. What should I do?

  76. 25 Feb 2002 at 21:45

    Pathetic article, this code would never stand up in the real world, not scalable in the slightest.
    How about some REAL multithreaded code that would actually stand up to a real world scenario...


  77. 30 Jan 2002 at 18:17

    Hello,
    I am using a phone line and a modem to connect to internet like my friends.


    We have different ISPs, is it possible to write a chat program with WinSock in VB? If yes when will it work and how? I mean will chat programs which are written in VB with WinSock work when Server and Clients computers are connected to different ISPs With modem? Or something else is needed?


    Please reply to: "m_jahedbozorgan@hotmail.com"
    Best Regards
    M. Jahedbozorgan

  78. 04 Jan 2002 at 11:20

    There is, but you have to send the data, not the file itself.
    Do something like this:


    Code:

    Dim iLines, iLine As Integer
    Dim sLine As String
    'Read how many lines are in the file
    '
    Winsock1.SenData "LINES " & iLines
    While Not EOF(1)
       'Read a line
       '
       'Send it
       Winsock1.SendData "LINE " & iLine & " "sLine
       iLine = iLine + 1
    Wend


    I think you got the idea by now.

  79. 04 Jan 2002 at 11:09

    I ment the same thing


    mIRC and other IRC chat clints are somehow able to connect to one port, without getting an error. The same do the servers, they can hold many clients on 1 port. I've checked all ports, they don't direct and don't use control arrays. HOW???.


    The mystery will still remain...
    I think...

  80. 10 Dec 2001 at 02:53

    Can i use a port for 2 clients at the same time?!?!?
    Case no what i can do!?

  81. 08 Dec 2001 at 22:03

    Is there a way to modify this to send text files?

  82. 30 Oct 2001 at 16:47

    You need to create a Control array of WinSock controls... set the first winsock controls index property to 0. Then, you can create additional connections by doing


    Load WinSockControl (1) 'next winsock control
    'connect, or whatever
    Load WinSockControl (2) 'next winsock control

  83. 30 Oct 2001 at 10:23

    How to connect to multiple clients? Like Chats do? If I want to connect another client to server, it won't connect, it gives an error. What should I do?

  84. 01 Jan 1999 at 00:00

    This thread is for discussions of WinSock Control.

Leave a comment

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

AddThis

Related podcasts

  • ASP.NET Caching and Performance

    Steve Smith, owner of ASP Alliance and Lake Quincy Media joins us today to teach us about some hidden gems in ASP.NET caching and performance. Steve’s expertise in this area comes from first-hand experience as Lake Quincy’s ad system serves over 60 requests per second and handles over 150 million...