Page 1 of 2 12 LastLast
Results 1 to 40 of 62

Thread: [Guide] Winsock - Chat Application

  1. #1

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    [Guide] Winsock - Chat Application

    Ok Ladies gents, and frogs, i have edited the guide slightly and included the source code now, I hope people find this usefull

    I have included it in the format of a word document with the source code all zipped up together,

    PINO-
    Attached Files Attached Files
    Last edited by Pino; Jan 12th, 2005 at 12:38 PM.

  2. #2
    G&G Moderator chemicalNova's Avatar
    Join Date
    Jun 2002
    Location
    Victoria, Australia
    Posts
    4,246

    Re: [Guide] Winsock - Chat Application

    Originally posted by Pino

    Maybe a mod could make this a sticky
    Or you could post it in the CodeBank part of the forums..

    Phreak

    Visual Studio 6, Visual Studio.NET 2005, MASM

  3. #3
    Frenzied Member thegreatone's Avatar
    Join Date
    Aug 2003
    Location
    Oslo, Norway. Mhz:4700 x4
    Posts
    1,333

    Re: [Guide] Winsock - Chat Application

    Bloody Ace, cheers mate that cleared up alot of my problems with winsock.

    And made my latest project much easier to do
    Zeegnahtuer?

  4. #4

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    Quote Originally Posted by thegreatone
    Bloody Ace, cheers mate that cleared up alot of my problems with winsock.

    And made my latest project much easier to do
    I'm so glad it helped

    Comments like that make me want to write more guides

    Thanks

  5. #5
    Lively Member
    Join Date
    Oct 2004
    Location
    UK
    Posts
    119

    Re: [Guide] Winsock - Chat Application

    one word, fanastic. ty for sharing this, I got a warm buzz when I compile it and tested it .

    one question tho about the server, I was thinking bout similar where the server is actually on a website n friends connect to the server. An alternatively rather then someone having to have the server up n running where as it runs on a website's host. Possible features would include voice communicating etc basically a neat chat room similar to teamspeak if you have used it. Would this be hard?

  6. #6

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    Quote Originally Posted by Shadows
    one word, fanastic. ty for sharing this, I got a warm buzz when I compile it and tested it .

    one question tho about the server, I was thinking bout similar where the server is actually on a website n friends connect to the server. An alternatively rather then someone having to have the server up n running where as it runs on a website's host. Possible features would include voice communicating etc basically a neat chat room similar to teamspeak if you have used it. Would this be hard?
    Thanks for the comments, you cant host the server on a website, because they usually dont let you host .exe files and if they do its very expensive

    Pino

  7. #7
    Lively Member
    Join Date
    Oct 2004
    Location
    UK
    Posts
    119

    Re: [Guide] Winsock - Chat Application

    ye I know, I was thinking about the server being programming in php or java and the client made in vb6. I'm still learning but from what I've heard, php has its own socket use for communicating with external programs or something on those lines. Basically winsock communicating with the alternative for php

  8. #8
    Lively Member CodeBlock's Avatar
    Join Date
    May 2005
    Location
    The_Universe.Milky_Way. Solar_System.Inner_Ring. The_Earth.Asia. India.TN. Chennai. Home_Sweet_Home
    Posts
    85

    Re: [Guide] Winsock - Chat Application

    Sorry Pino,

    It just destroys one small point. Your's is just a Peer to Peer Chat application, Meaning: One Server for One Client. So you have a PeerServer which accepts connection for one client and a PeerClient which can connect only to one server. A Server, in complete, accepts more than one request from the client side.

    To achieve this u need an Array of Winsock.
    So, this code:

    VB Code:
    1. Private Sub Winsock_ConnectionRequest(ByVal requestID As Long)
    2.     Winsock.Close 'this resets our socket ready to accept the incoming connection
    3.     Winsock.Accept requestID 'accept the connection!
    4. End Sub

    becomes

    VB Code:
    1. ' Place a new Winsock array exclusively for Clients - wskClients(0) is the default
    2. Private Sub Winsock_ConnectionRequest(ByVal requestID As Long)
    3.  
    4.     newClient = wskClients.UBound + 1
    5.     Load wskClients(newClient)
    6.  
    7.     wskClients(newClient).Accept requestID 'accept the connection with our new Winsock
    8.    ' So the Server continues to listen for more clients
    9. End Sub

    Anyway, Very Good code for beginners.

    Regards

    HTH
    Neo

    Edit: Fixed vbcode tags - Hack
    Last edited by CodeBlock; May 18th, 2005 at 09:05 AM.

  9. #9

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    What i tend to find is hen learning to use winsock beginners find array very confusing and hence this aplication isnt Mulit-User chat but a very simple 2 person chat which demonstrates how to start a server connect and send data the fundementals of winsock, then if they wish to take it any further they can start to look at arrays but as I say this example is designed to be kept simple, i dont want to over complecate and confuse people


    Anyhows i appriciate your comments and if you wish why not write up a guide demonstarating how to sue control arrays with winsock. I am in the middle of writing up the Network FAQ so if the guide is good I can link to it.


  10. #10

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    Also just to pick up on the code you posted,

    becomes
    VB Code:
    1. ' Place a new Winsock array exclusively for Clients - wskClients(0) is the default
    2. Private Sub Winsock_ConnectionRequest(ByVal requestID As Long)
    3.  
    4. newClient = wskClients.Count + 1
    5. Load wskClients(newClient)
    6.  
    7. wskClients(newClient).Accept requestID 'accept the connection with our new Winsock
    8. ' So the Server continues to listen for more clients
    9. End Sub
    Faior enough but what happens if we have lots of clients connecting and then some leave?Over time you will have a large amount of un-used sockets which are just wasting server memory which isnt good if we are developing a serve rof some kind.

    also this line

    VB Code:
    1. Private Sub Winsock_ConnectionRequest(ByVal requestID As Long)

    if we are using an array should be....

    VB Code:
    1. Private Sub Winsock_ConnectionRequest([B]index as integer,[/B]ByVal requestID As Long)

    Just to clear that up incase anyone takes anythign from this post.

    Pino

  11. #11
    Lively Member CodeBlock's Avatar
    Join Date
    May 2005
    Location
    The_Universe.Milky_Way. Solar_System.Inner_Ring. The_Earth.Asia. India.TN. Chennai. Home_Sweet_Home
    Posts
    85

    Resolved Re: [Guide] Winsock - Chat Application

    Hey Pino,

    Why dont you read my previous post properly! In a hurry i have forgot to close the [ vbcode ] properly. So, it ended up with a code line that made you not to notice the first line. I have specified you to create a new Winsock and name it as wskClients exclusively for Clients, and NOT to make the existing Winsock as an array. That way u need to change a lot of code, such as, to replace with Winsock(0) with Winsock everywhere.

    So, y do you need this:
    VB Code:
    1. Private Sub Winsock_ConnectionRequest([color=red]Index As Integer,[/color] ByVal requestID As Long)

    I closely look at codes before posting, So dont worry . (Please look at my code carefully) My Code is correct:

    VB Code:
    1. Private Sub Winsock_ConnectionRequest(ByVal requestID As Long)

    Because, it is only wskClients an Array and not the listening Winsock object.

    Also, regarding the code:
    I just gave a starting idea. If you want to continue, i will do it. It is obvious that u have to unload objects when they get closed, isnt it?

    VB Code:
    1. Private Sub wskClients_Error(Index As Integer, ByVal Number As Integer, _
    2. Description As String, ByVal Scode As Long, ByVal Source As String, ByVal _
    3. HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)
    4.  
    5.       Call wskClients_Close(Index)
    6.  
    7. End Sub
    8.  
    9. ' Clean up code
    10. Private Sub wskClients_Close(Index As Integer)
    11.     wskClients(Index).Close
    12.     Unload wskClients(Index)
    13. End Sub

    But there is one small modification instead of using the .Count, its better to use the .UBound variable

    So the Index variable keeps increasing. But the objects get unloaded. At point of time, when all clients quit all winsocks unload. I have a graph on Winsocks Clients Connection/DisConnection Time Line:


    HTML Code:
    Slots Marked with x are loaded wskClients
    
     No.  Clients
    
          1  2  3  4  5  6  7  8  9  10  .Count .UBound+1 <-- New Empty WinSock
        _____________________________________________________
     1  | x					1       2      New Client Connects
     2  | x  x				2       3      New Client Connects
     3  | x  x  x				3       4      New Client Connects
     4  | x     x                           2       4      Client 2 DisConnects
     5  | x     x  x                        3       5      New Client Connects
     6  | x     x  x  x                     4       6      New Client Connects
     7  | x     x     x                     3       7      Client 4 Disconnects 
     8  | x     x                           2       4      Client 5 Disconnects
     9  | x     x  x                        3       5      New Client Connects
     10 | x        x                        2       5      Client 3 Disconnects
     11 | x        x  x                     3       6      New Client Connects
     12 |          x  x                     2       6      Client 1 Disconnects
     13 |             x                     1       6      Client 4 Disconnects
     14 |                                   0       1      Client 5 Disconnects
     15 | x                                 1       2      Cycles again in some combination
     16 |___________________________________________   


    Hehe.. just a research i made.. to explain...

    This means (.UBound + 1) always refers to a New Client

    So the code becomes:
    VB Code:
    1. ' Place a new Winsock array exclusively for Clients - wskClients(0) is the default
    2. Private Sub Winsock_ConnectionRequest(ByVal requestID As Long)
    3.  
    4.     newClient = wskClients.UBound + 1 ' instead of .Count + 1
    5.     Load wskClients(newClient)
    6.  
    7.     wskClients(newClient).Accept requestID 'accept the connection with our new Winsock
    8.    ' So the Server continues to listen for more clients
    9. End Sub
    10.  
    11.  
    12. Private Sub wskClients_Error(Index As Integer, ByVal Number As Integer, _
    13. Description As String, ByVal Scode As Long, ByVal Source As String, ByVal _
    14. HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)
    15.  
    16.       Call wskClients_Close(Index)
    17.  
    18. End Sub
    19.  
    20. ' Clean up code
    21. Private Sub wskClients_Close(Index As Integer)
    22.     wskClients(Index).Close
    23.     Unload wskClients(Index)
    24. End Sub

    Any Comments?

    HTH
    Neo

  12. #12

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    Yes please create a new thread if you wish to continue this one i'd prefer to keep this one simple as no to confuse the target programmer.

    And if i read your code in-correctly i appoligise.


  13. #13
    Hyperactive Member
    Join Date
    Aug 2004
    Posts
    277

    Re: [Guide] Winsock - Chat Application

    hi..
    i am stuck with the broadcast stuff...how???
    this is my code here..--->

    VB Code:
    1. [COLOR=Green]Option Explicit
    2.  
    3. Dim buffer() As Byte
    4. Dim lBytes As Long
    5. Dim temp As String
    6. Dim index As Long
    7. Private Sub cmdBrowse_Click()
    8.   dlg.ShowOpen
    9.   txtFile = dlg.FileName
    10. End Sub
    11.  
    12. Private Sub cmdSend_Click()
    13. Dim index As Long
    14.   cmdSend.Enabled = False
    15.   lBytes = 0
    16.   ReDim buffer(FileLen(dlg.FileName) - 1)
    17.   Open dlg.FileName For Binary As 1
    18.   Get #1, 1, buffer
    19.   Close #1
    20.   Load wsTCP(1)
    21.      wsTCP(1).RemoteHost = "255.255.255.255"
    22.   wsTCP(1).RemotePort = 1111
    23.   wsTCP(1).Connect
    24.   lblStatus = "Connecting..."
    25. End Sub
    26.  
    27. Private Sub wsTCP_Close(index As Integer)
    28.   lblStatus = "Connection closed"
    29.   Unload wsTCP(1)
    30. End Sub
    31.  
    32. Private Sub wsTCP_Connect(index As Integer)
    33.    Dim i As Long
    34.    ' Loop through the control array of clients and send the data on each one.
    35.    For i = 1 To wsTCP.UBound
    36.            wsTCP(index).SendData dlg.FileTitle & vbCrLf
    37.    Next i
    38.  
    39. End Sub
    40.  
    41. Private Sub wsTCP_DataArrival(index As Integer, ByVal bytesTotal As Long)
    42.   wsTCP(index).GetData temp
    43.   If InStr(temp, vbCrLf) <> 0 Then temp = Left(temp, InStr(temp, vbCrLf) - 1)
    44.   If temp = "OK" Then
    45.     wsTCP(index).SendData buffer
    46.   Else
    47.     lblStatus = "Something wrong"
    48.     Unload wsTCP(index)
    49.     cmdSend.Enabled = True
    50.   End If
    51. End Sub
    52.  
    53. Private Sub wsTCP_SendComplete(index As Integer)
    54.   If temp = "OK" Then
    55.     lblStatus = "Send complete"
    56.     temp = ""
    57.     Unload wsTCP(1)
    58.     cmdSend.Enabled = True
    59.   End If
    60. End Sub
    61.  
    62. Private Sub wsTCP_SendProgress(index As Integer, ByVal bytesSent As Long, ByVal bytesRemaining As Long)
    63.   If temp = "OK" Then
    64.     lBytes = lBytes + bytesSent
    65.     lblStatus = lBytes & " out of " & UBound(buffer) & " bytes sent"
    66.   End If
    67. End Sub[/COLOR]

    need help urgently...
    really appreciated a lot..
    thanks..

    ocw
    Last edited by Hack; Aug 1st, 2005 at 05:57 AM.

  14. #14
    Hyperactive Member
    Join Date
    Aug 2004
    Posts
    277

    Re: [Guide] Winsock - Chat Application

    Quote Originally Posted by CodeBlock
    Sorry Pino,

    It just destroys one small point. Your's is just a Peer to Peer Chat application, Meaning: One Server for One Client. So you have a PeerServer which accepts connection for one client and a PeerClient which can connect only to one server. A Server, in complete, accepts more than one request from the client side.

    To achieve this u need an Array of Winsock.
    So, this code:

    VB Code:
    1. Private Sub Winsock_ConnectionRequest(ByVal requestID As Long)
    2.     Winsock.Close 'this resets our socket ready to accept the incoming connection
    3.     Winsock.Accept requestID 'accept the connection!
    4. End Sub

    becomes

    VB Code:
    1. ' Place a new Winsock array exclusively for Clients - wskClients(0) is the default
    2. Private Sub Winsock_ConnectionRequest(ByVal requestID As Long)
    3.  
    4.     newClient = wskClients.UBound + 1
    5.     Load wskClients(newClient)
    6.  
    7.     wskClients(newClient).Accept requestID 'accept the connection with our new Winsock
    8.    ' So the Server continues to listen for more clients
    9. End Sub

    Anyway, Very Good code for beginners.

    Regards

    HTH
    Neo

    Edit: Fixed vbcode tags - Hack

    hi Hack,

    i am doing problem this winsock. please enlighten me..

    newClient = wskClients.UBound + 1
    Load wskClients(newClient)

    wskClients(newClient).Accept requestID 'accept the connection with our new Winsock


    what is the "WskClient" doing in the prog?

    ???
    ocw

  15. #15

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    WskClients is the name of the winsock control array,

    Its just renamed from Winsock1.

    The code above finds out which number is one above the UBound array and then creates a new socket on that number.

    Is that what you mean?

    Guys I must stress the main intention of this guide was to provide a simple beginning the winsock IE one client one server its going a bit beyond that now.

  16. #16
    Hyperactive Member
    Join Date
    Aug 2004
    Posts
    277

    Re: [Guide] Winsock - Chat Application

    hi guys..

    i have tried numerous times on this Winsock based on the guide lines and points mentioned in this forum. apart from so many connection_request methods discussed, i find it very interesting. HOwever, i have a question on how to send the data? if i have 10 listener waiting for my data, how can i broadcast to them? if i open two listener on different station within the network listening on the same port(port 1111), the error will pop out saying something like " adddress been used" and Control array element '2' doesn't exist. i really need yours guidances..

    [vb code]

    sending method

    Private Sub cmdSend_Click()

    Dim Index As Long
    Dim i As Integer
    cmdSend.Enabled = False
    lBytes = 0
    ReDim buffer(FileLen(dlg.FileName) - 1)
    Open dlg.FileName For Binary As 1
    Get #1, 1, buffer
    Close #1


    For i = 1 To wsClient.UBound + 1
    Load wsClient(i) 'wsClient as my WinSock TCP protocol
    wsClient(i).RemoteHost = "192.168.122.255" 'my broadcast address
    wsClient(i).RemotePort = 1111
    wsClient(i).Connect
    lblStatus = "Connecting..."

    Next i

    [/vb code]

    should i loop the wsClient like the way it had mentioned in this forum??? i have a similar connection_request methodas in the forum.


    [vb code]
    Private Sub wsClient_Connect(Index As Integer)
    Dim i As Long

    ' Loop through the control array of clients and send the data on each one.
    For i = 1 To wsClient.UBound + 1
    wsClient(i).SendData dlg.FileTitle & vbCrLf
    Next i
    End Sub

    [/vb code]

    Greatly appreciated...
    ocw
    Last edited by ocw; Jun 18th, 2005 at 08:38 AM.

  17. #17

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    To send a message to all clients connected do this,

    VB Code:
    1. for i = 0 to winsock.ubound - 1
    2.         if winsock(i).state = sckconnected then
    3.                 wisnock(i).senddata "Data"
    4.         end if
    5.    doevents
    6. next i

    thats all you need to do, no need to open up any more connectiosn etc.

  18. #18

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    this amkes no sence either...
    VB Code:
    1. For i = 1 To wsClient.UBound + 1
    2. Load wsClient(i) 'wsClient as my WinSock TCP protocol
    3. wsClient(i).RemoteHost = "192.168.122.255" 'my broadcast address
    4. wsClient(i).RemotePort = 1111
    5. wsClient(i).Connect
    6. lblStatus = "Connecting..."
    7.  
    8. Next i

    why are you looping to connect?

  19. #19

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    post me your client and sever applications.

    pino

  20. #20
    Hyperactive Member
    Join Date
    Aug 2004
    Posts
    277

    Re: [Guide] Winsock - Chat Application

    Quote Originally Posted by Pino
    To send a message to all clients connected do this,

    VB Code:
    1. for i = 0 to winsock.ubound - 1
    2.         if winsock(i).state = sckconnected then
    3.                 wisnock(i).senddata "Data"
    4.         end if
    5.    doevents
    6. next i

    thats all you need to do, no need to open up any more connectiosn etc.
    hihi..

    what about the code below?
    [vb code]
    Load wsClient(1)
    wsClient(1).RemoteHost = "192.168.122.222" 'not a broadcast address (should i place a broadcast add to 192.168.122.255?)
    wsClient(1).RemotePort = 1111
    wsClient(1).Connect
    lblStatus = "Connecting..."
    [/vb code]

    should i made any changes to it?

    real thanks..

    ??
    ocw

  21. #21

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    What is that code supposed to do? Looks very strange.....

  22. #22
    Hyperactive Member
    Join Date
    Aug 2004
    Posts
    277

    Re: [Guide] Winsock - Chat Application

    Quote Originally Posted by Pino
    What is that code supposed to do? Looks very strange.....
    hihi..

    thanks Pino, this is my application. the objective of my application should be able to broadcast the all stations within the network.

    real thanks..

    ??
    ocw
    Attached Files Attached Files

  23. #23
    Hyperactive Member
    Join Date
    Aug 2004
    Posts
    277

    Re: [Guide] Winsock - Chat Application

    Quote Originally Posted by Pino
    this amkes no sence either...
    VB Code:
    1. For i = 1 To wsClient.UBound + 1
    2. Load wsClient(i) 'wsClient as my WinSock TCP protocol
    3. wsClient(i).RemoteHost = "192.168.122.255" 'my broadcast address
    4. wsClient(i).RemotePort = 1111
    5. wsClient(i).Connect
    6. lblStatus = "Connecting..."
    7.  
    8. Next i

    why are you looping to connect?
    sorry for the weird code given. i just want to try if i could send the data to all the stations within the network. i am not sure on winsock.

    sigh...
    ocw

  24. #24

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    what does the app do? I can see deleting files, raises alarm bells....

  25. #25

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    Ok,

    Wisnock(0) allwasy listens its the only one listening. from here it loads a new socket.

    cahnge these parts,

    VB Code:
    1. Private Sub ws_sev_ConnectionRequest(index As Integer, ByVal requestID As Long)
    2.   Dim i As Long
    3.  
    4.     i = wskClients.UBound + 1
    5.     Load ws_sev(newClient)
    6.  
    7.     ws_sev(newClient).Accept requestID
    8. End Sub

    and change this also

    VB Code:
    1. Private Sub cmdRun_Click()
    2.   If cmdRun.Caption = "Run" Then
    3.     cmdRun.Caption = "Stop"
    4.    
    5.     ws_sev(0).LocalPort = 1111
    6.     ws_sev(0).Listen
    7.    
    8.   Else
    9.     ws_sev(0).Close
    10.     cmdRun.Caption = "Run"
    11.   End If
    12. End Sub

  26. #26
    Hyperactive Member
    Join Date
    Aug 2004
    Posts
    277

    Re: [Guide] Winsock - Chat Application

    Quote Originally Posted by Pino
    Ok,

    Wisnock(0) allwasy listens its the only one listening. from here it loads a new socket.

    cahnge these parts,

    VB Code:
    1. Private Sub ws_sev_ConnectionRequest(index As Integer, ByVal requestID As Long)
    2.   Dim i As Long
    3.  
    4.     i = wskClients.UBound + 1
    5.     Load ws_sev(newClient)
    6.  
    7.     ws_sev(newClient).Accept requestID
    8. End Sub

    and change this also

    VB Code:
    1. Private Sub cmdRun_Click()
    2.   If cmdRun.Caption = "Run" Then
    3.     cmdRun.Caption = "Stop"
    4.    
    5.     ws_sev(0).LocalPort = 1111
    6.     ws_sev(0).Listen
    7.    
    8.   Else
    9.     ws_sev(0).Close
    10.     cmdRun.Caption = "Run"
    11.   End If
    12. End Sub
    hihi..

    i have change the code. now the error throws "connection close" at the statue label.

    ocw

  27. #27

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    i didnt look through the rest of the code, i havent had chance, and i'm not runnign the program, until you tell me what it does, I cant help you any further

    Pino

  28. #28
    Hyperactive Member
    Join Date
    Aug 2004
    Posts
    277

    Re: [Guide] Winsock - Chat Application

    Quote Originally Posted by Pino
    what does the app do? I can see deleting files, raises alarm bells....
    hihi..

    the application will override the file if there are duplicate file name. the main objective to this applicaition is to send the file to all stations within the network (broadcasting)...

    now, the application only able to send to the one port or one station.


    thanks Pino.

    Best regards
    ocw

  29. #29

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    I cant make head nor tail of the code, the server is supposed to send the file out right?

    I think you best go back to basics, cut all the disabling commands etc, and just stay winsock, then really focus on what is supposed to go on.

    Pino

  30. #30
    Hyperactive Member
    Join Date
    Aug 2004
    Posts
    277

    Unhappy Re: [Guide] Winsock - Chat Application

    Quote Originally Posted by Pino
    I cant make head nor tail of the code, the server is supposed to send the file out right?

    I think you best go back to basics, cut all the disabling commands etc, and just stay winsock, then really focus on what is supposed to go on.

    Pino
    sorry fro the messy codes, the server is suppose to listen for the data, while the client is suppose to send the data. by using the localhost ip, i am able to send to my station destop. but when i change the RemoteIP to the "192.168.122.255" the broadcast add, it fails to broadcast the data, even to my station.

    thus, i have wondering is my connection_request and the sending of data is correct.

    thanks pal
    ocw

  31. #31
    PowerPoster
    Join Date
    Feb 2002
    Location
    Canada, Toronto
    Posts
    5,802

    Re: [Guide] Winsock - Chat Application

    First of all, you can't broadcast with TCP only UDP.
    And with UDP, the broadcast IP is 255.255.255.255 (and it works only for local network)

    The example Pino gave to broadcast, does not really broadcast, it's simply sending a message to everyone who is connected.
    For example if you have 10 connections, and you want to send the same message to all 10, then you send to the first one, then the second, and so on.
    That means that if you have a message that is 100 bytes (lets say), you will end up sending 100 * 10 = 1000 bytes. Wich is NOT broadcast.

    Broadcast means you send 10 bytes ONCE and everyone gets the message.

    Also, what you want is multicast, not broadcast, you want a select # of people to get the message, not EVERYONE ?

    So, if you REALLY want to broadcast you have to switch to UDP protocol. Also don't forget that even that, works only for local network.

  32. #32
    Lively Member
    Join Date
    Jul 2005
    Posts
    73

    Re: [Guide] Winsock - Chat Application

    im having some big problms with my code can someone tell me why when the client sends something it doesnt appear in the server screen and am i doing the multiple connections thing right?


    Server
    VB Code:
    1. Dim msgarrived As String
    2. Dim i As Integer
    3.  
    4. Private Sub cmdsend_Click()
    5. For i = 0 To server.ubound - 1
    6.         If server(i).State = sckConnected Then
    7. server(i).SendData txtnickname.Text & ": " & txtmsg.Text
    8. txtchat.Text = txtnickname.Text & ": " & txtmsg.Text & vbNewLine
    9. txtmsg.Text = ""
    10.         End If
    11.    DoEvents
    12. Next i
    13. End Sub
    14.  
    15.  
    16. Private Sub Winsock_ConnectionRequest(ByVal requestID As Long)
    17.  
    18.     newClient = server.ubound + 1
    19.     Load server(newClient)
    20.  
    21.     server(newClient).Accept requestID
    22. End Sub
    23.  
    24. Private Sub server_DataArrival(Index As Integer, ByVal bytesTotal As Long)
    25. server(i).GetData msgarrived
    26. txtchat.Text = msgarrived & vbNewLine
    27. End Sub
    28.  
    29. Private Sub server_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)
    30. Call server_Close(Index)
    31. End Sub
    32.  
    33. Private Sub server_Close(Index As Integer)
    34.     server(Index).Close
    35.     Unload server(Index)
    36. End Sub


    Client
    VB Code:
    1. Option Explicit
    2. Dim msgarrived As String
    3. Dim i As Integer
    4.  
    5.  
    6. Private Sub cmdconnect_Click()
    7. client(i).Connect txtip.Text, txtportnum.Text
    8. MsgBox "Connected To " & txtip.Text
    9. End Sub
    10.  
    11. Private Sub cmdsend_Click()
    12. For i = 0 To client.ubound - 1
    13.         If client(i).State = sckConnected Then
    14. client(i).SendData txtnickname.Text & ": " & txtmsg.Text
    15. txtchat.Text = txtnickname.Text & ": " & txtmsg.Text & vbNewLine
    16. txtmsg.Text = ""
    17.         End If
    18.    DoEvents
    19. Next i
    20.  
    21. End Sub
    22.  
    23. Private Sub Winsock_ConnectionRequest(ByVal requestID As Long)
    24.  
    25.     newClient = server.ubound + 1
    26.     Load client(newClient)
    27.  
    28.     client(newClient).Accept requestID
    29. End Sub
    30.  
    31. Private Sub client_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)
    32. Call client_Close(Index)
    33. End Sub
    34.  
    35. Private Sub client_Close(Index As Integer)
    36.     client(Index).Close
    37. End Sub

  33. #33

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    change,

    VB Code:
    1. Private Sub server_DataArrival(Index As Integer, ByVal bytesTotal As Long)
    2. server(i).GetData msgarrived
    3. txtchat.Text = msgarrived & vbNewLine
    4. End Sub

    on the server to say

    VB Code:
    1. Private Sub server_DataArrival(Index As Integer, ByVal bytesTotal As Long)
    2. server(index).GetData msgarrived
    3. txtchat.Text = msgarrived & vbNewLine
    4. End Sub

    that will work!

  34. #34
    Lively Member CodeBlock's Avatar
    Join Date
    May 2005
    Location
    The_Universe.Milky_Way. Solar_System.Inner_Ring. The_Earth.Asia. India.TN. Chennai. Home_Sweet_Home
    Posts
    85

    Re: [Guide] Winsock - Chat Application

    A Good Muliti Connection Chat App should have some strict rules:

    Server Rules:
    1. Must Run only *ONCE* and listen at a specific port
    2. Must Accept connections from clients by transfering the incoming connection to a new Socket, thus keeping the Listening socket available for more clients to connect.
    3. Cannot have a User-Interface (its not a Client, please remember) to interact with a User (Except for Admin Messages and advanced stuff)
    4. may try to redirect most messages for simplicity
    5. Should follow a Protocol common to both the client and the server. Protocol may be simple from user-defined to complex such as IRC, IRCX ... etc

    Client Rules:

    1. Should Connect to a Server using just one Winsock - NO ARRAYS
    2. Any new client starting, should start on its own new Application (new process)
    4. Can have User Interface for Client Interaction
    3. Follow the same protocol as supported by the Server


    See whether u follow the above rules

    For a person to chat with another person, 3 apps will run at the least.

    One will be the server and the other two will be the two person's client app.

    So if Person 1 wants to send message to Person 2, the client1 first contacts the server the server then send the message to client 2.

    Thus, the server is like a mediator.

    Due to these reasons, u have to first remove text boxes from ur server app. The Server app cannot act like a client, hehe, Can it?

    And Regarding Protocols, its better to send your messages with some extra commands along with ur message. And dont forget to seperate your message with a delimiter. 99% of Chat Clients use vbCrLf as the message seperator.

    So your code can look like this after some modifications:

    Server:
    VB Code:
    1. Dim msgarrived As String
    2. Dim i As Integer
    3.  
    4. 'Private Sub cmdsend_Click()
    5. 'For i = 0 To server.ubound - 1
    6. '        If server(i).State = sckConnected Then
    7. '            server(i).SendData txtnickname.Text & ": " & txtmsg.Text
    8. '            txtchat.Text = txtnickname.Text & ": " & txtmsg.Text & vbNewLine
    9. '            txtmsg.Text = ""
    10. '        End If
    11. '   DoEvents
    12. 'Next i
    13. 'End Sub
    14.  
    15. Private Sub Winsock_ConnectionRequest(ByVal requestID As Long)
    16.  
    17.     newClient = server.ubound + 1
    18.     Load server(newClient)
    19.  
    20.     server(newClient).Accept requestID
    21. End Sub
    22.  
    23. Private Sub server_DataArrival(Index As Integer, ByVal bytesTotal As Long)
    24. Dim Data As String
    25. server(Index).GetData Data, vbString
    26.    
    27.     ' If we have any data remaining from the previous DataArrival Call
    28.     Data = Messages(Index) & Data
    29.  
    30.     Dim Messages() As String
    31.    
    32.     Messages = Split(Data, vbCrLf)
    33.     For i = LBound(Messages) To UBound(Messages) - 1
    34.         ParseMessage Messages(i)
    35.     Next i
    36.     ' We are adding the last message as buffer to prevent data loss
    37.     server(Index).Tag = Messages(i)
    38. End Sub
    39.  
    40. Private Sub server_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)
    41. Call server_Close(Index)
    42. End Sub
    43.  
    44. Private Sub server_Close(Index As Integer)
    45.     server(Index).Close
    46.     Unload server(Index)
    47. End Sub
    48.  
    49.  
    50. Sub ParseMessage(Message As String)
    51. Dim CMDs() As String
    52. Dim RealMessage As String
    53. Dim i As Long
    54.  
    55.     ' Message can be like
    56.     ' MSG MyNickName :hi all
    57.     ' PM MyNickName CodeBlock :hi mate ;)
    58.  
    59.     ' Seperate Commands from Real Message, Colon ":" is our seperator
    60.     i = InStr(1, Message, ":")
    61.     RealMessage = Mid$(Message, i + 1)
    62.    
    63.     ' get the commands such as MSG or PM CodeBlock ... etc
    64.     Message = Left$(Message, i - 1)
    65.     CMDs = Split(Message, " ")
    66.    
    67.     Select Case CMDs(0)
    68.         Case "MSG":
    69.             ' Cmds(1) has the nickname of the sender
    70.             ' This command means message to all
    71.             For i = 0 To UBound(server)
    72.                 ' MSG SenderNick:Real Message
    73.                 server(i).SendData "MSG " & CMDs(1) & ":" & RealMessage
    74.             Next i
    75.         Case "PM":
    76.             ' Cmds(1) has the nickname of the receiver
    77.             '...
    78.     End Select
    79. End Sub

  35. #35

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    Please, you have to look at a users ability and where they are in, learning or expert. he/She is clearly learning so this stuff is not nessercery. And a server can have an interface/control pannel.

    As i have mentioned before please create anew thread if you wish to make an advanced guide. Again I will quote myself. Before i have to have this thread split.

    Guys I must stress the main intention of this guide was to provide a simple beginning the winsock IE one client one server its going a bit beyond that now.

  36. #36
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: [Guide] Winsock - Chat Application

    I never liked leaving holes in my array of servers so I use this simple function to load the next server.
    VB Code:
    1. Function LoadNextServer(wsServer) As Long
    2. Dim wsck
    3. Dim i As Long
    4.     i = 0
    5.     For Each wsck In wsServer
    6.         If wsck.Index > i Then
    7.             LoadNextServer = i
    8.             Load wsServer(i)
    9.             Exit Function
    10.         Else
    11.             i = i + 1
    12.         End If
    13.     Next
    14.     LoadNextServer = i
    15.     Load wsServer(i)
    16. End Function

    Then you would call it like this
    VB Code:
    1. Private Sub Server_ConnectionRequest(Index As Integer, ByVal requestID As Long)
    2. Dim newClient As Long
    3.     If Index = 0 Then
    4.     'this is the listening server
    5.     'load a new control to talk to this client
    6.         newClient = LoadNextServer(Server)
    7.         Server(newClient).Accept requestID
    8.         Server(newClient).SendData "Hello: you are connected"
    9.     End If
    10. End Sub

    Pino, sorry if you think this is too advanced, but I think it is basic.

  37. #37
    Hyperactive Member
    Join Date
    Apr 2004
    Location
    Philippines
    Posts
    285

    Re: [Guide] Winsock - Chat Application

    i need clarification on this one. in the winsock array, say for example i loaded 5 winsocks because there are 5 clients that connected, if the starting index for my winsock array is 0, then winsock.ubound would be 4,right? and when another client would connect, i would load winsock(5) to accept that connection, and calling winsock.ubound would give me 5, is this right?

    and then for example winsock(1) is closed and unloaded, only 5 winsocks would be left because winsock(1) is removed but winsock.ubound would still be 5, right? because the array index would not rollback even if you unload an item that is part of the array.

    so i guess in a multi client-server application, it is not safe to iterate thru all clients using something like:
    VB Code:
    1. for i=0 to ubound(sckClients)
    2.     sckClients(i).senddata "blah...blah...."
    3. next i

    it is better i think to use a for each loop.

  38. #38

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    Ok, here is how it works

    Winsock(0) allways listens, when it gets a connection request it passes it on to the next avalible winsock,

    Winsock(1), Winsock (2) etc

    as for the loop here is how to senddata to all connected clients,

    VB Code:
    1. For i = winsock.ubound - 1
    2.         if winsock(i).state = sckconnected then
    3.                winsock(i).senddata "hello"
    4.          end if
    5.    doevents
    6. next i

    Hope that helps, if you have any furthur questions could you make a new post in the network section?

    Thanks

    Pino

  39. #39
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: [Guide] Winsock - Chat Application

    VB Code:
    1. For i = winsock.ubound - 1
    2.         if winsock(i).state = sckconnected then
    3.                winsock(i).senddata "hello"
    4.          end if
    5.    doevents
    6. next i
    I think Pino was half asleep when he wrote this. For one thing it won't work if a control has been unloaded.

    Instead I would do this
    VB Code:
    1. Dim wsk As Winsock
    2.     For Each wsk In Winsock
    3.         If wsk.State = sckConnected Then _
    4.             wsk.SendData "Hello"
    5.     Next

  40. #40

    Thread Starter
    Super Moderator
    Join Date
    Dec 2003
    Posts
    4,787

    Re: [Guide] Winsock - Chat Application

    Nice polite person you are

    Can I ask how a sockect would be unloaded? seriosuly, I have never had a problem.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width