Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Chat with winsock

Posted on 1999-07-13
5
Medium Priority
?
641 Views
Last Modified: 2013-11-13
I am cufused as to how a client/server chat program works.
Or for that fact, is that the only type of chat program?
I have a working vb5 chat program sample but it only works
on one computer. Both the client and the server that is. The client part of the program is fine but the server program can not initiate a connection. So if i wanted to make a chat program and give it to a friend out of state to call me with, they woundnt be able to connect to me. They would always have to wait for me to connect to them. What i need
to know is, is there any sample code out there anywhere
that would help me understand how to use the winsock control
to create a chat program that works similar to icq? Or am i trying to use the wrong control for this project?
0
Comment
Question by:poorboy
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 

Expert Comment

by:flavio_sr
ID: 1524527
First set the remoteport and the remotehost if you will make the call... And look the code below to understand..

The CONNECT button:
Private Sub Command1_Click()
  Winsock1.close ´ "reset" the control
  Winsock1.connect
End Sub

To listen the calls:
Private Sub Form_Load()
 Winsock1.listen
End Sub

To accept a request:
Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long)
 Winsock1.Close ' "reset" the control
 Winsock1.Accept requestid ' accept the connection
End Sub

Get messages:
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
 Dim msg as string
 Winsock1.GetData msg, vbString
 RichTextBox1.Text = RichTextBox1.Text & msg & vbCrLf ´ I suggest the RTBox
End Sub

Sending Messages:
Private Sub Text1_KeyPress (KeyAscii as integer)
 If KeyAscii = vbKeyReturn then
  Winsock1.SendData Text1
  RichTextBox1.Text = RichTextBox1.Text & Text1 & vbCrLf
  Text1 = ""
end if
End Sub


0
 

Author Comment

by:poorboy
ID: 1524528
Please let  flavio_sr answer this. I have this code already. What i dont understand is who gets the client and who gets the server programs. Since the server cant initiate a connection wouldnt everyone i send a copy to just get the client app? The remote port i cant just set to a number like "1001" but the remote host is an ip address. If i need to contact the other person how do i obtain their ip address? Please help me if you can.
0
 

Accepted Solution

by:
WoodiE earned 600 total points
ID: 1524529
Poorboy,

Your in luck, i just ran across this code bout 2 days ago, i have tested it out and it works WONDERFUL, works kinda like ICQ or AIM, very very easy to follow and use. It's kinda long but it works.

'***************************************************************
'Windows API/Global Declarations for :Make a Client and Server Ch
'     at Room using Winsock
'***************************************************************
In code


'Name: Client and Server Chat Room (Server)



'Create a new form and add three(3) text boxes, one(1) command bu
'     tton, one(1) list box, and add the microsoft winsock control
'Change the name of the text boxes to tMain, and tSend, tIP, name
'     the command button cSnd, and name the list box lName
'Change the name of the winsock control to Wsck
'Change the caption of cSnd to "Send"
'Make tMain multiline = true, scrollbars = 2 - vertical, and lock
'     ed = true
'Make lName Sorted = true
'Make cSnd Default = true
'Insert the following code
'Declarations:
Dim Client As New Collection
Dim Names As New Collection
Const Indicator = ":':"


Private Sub cSnd_Click()


   
    'Send button
    'Make string to send
    txt$ = "ServerMaster: " & tSend.Text & Chr$(13) & Chr$(10)
    'Send to clients
    Call SendOut(txt$)
    'Clear Send text box
    tSend.Text = ""
End Sub



Private Sub Form_Load()


   
    'Clear Main text box
    tMain.Text = ""
    'We will be using UDP for this program because it does not establ
    '     ish a constant connection to another computer.
    'This will allow the server to keep "listening" for messages from
    '     other addresses on a network or the internet.
    Wsck.Protocol = sckUDPProtocol
    'Set your constant port (must be the same in clients)
    Wsck.LocalPort = 2367
    'Start listening
    Wsck.Bind
    'Add the server to the name list
    'This would allow you to make a list box in the client that could
    '     receive all of the names of the people in the room.
    RmIP = Wsck.LocalIP
    RmPt = 2367
    Names.Add Key:=RmIP, Item:="ServerMaster"
    'Display your IP Address for client use, and Computer Name for ne
    '     twork use.
    tIP.Text = RmIP & " / " & Wsck.LocalHostName
End Sub



Private Sub Form_Unload(Cancel As Integer)


    'End connection on Winsock
    Wsck.Close
    End
End Sub



Private Sub lName_DblClick()


   
    'Double-click an IP Address in the listbox
    'Create message with client NickName, IP Address, and Port
    txt$ = Names(lName.Text) & ", " & lName.Text & ", " & Client(lName.Text)
    MsgBox txt$, vbOKOnly, "User Information"
End Sub



Private Sub Wsck_DataArrival(ByVal bytesTotal As Long)


   
    'Winsock received a message
    'If an error occurs, ignore it and go on to the next command
    On Error Resume Next
    Dim DATA As String
    Dim DATA2 As String
    Dim Nam As String
    Dim MsgText As String
   
    'Retreive message in string format
    Wsck.GetData DATA, vbString
    'Get client's IP and Port
    RmIP = Wsck.RemoteHostIP
    RmPt = Wsck.RemotePort
   
    'Get first letter of message
    DATA2 = Left(DATA, 1)
    'Get the rest of the message
    DATA = Mid(DATA, 2)
    'If the message is a system command:


    If DATA2 = "s" Then
        'If a client wants to connect to the room:


        If Left(DATA, 20) = Indicator & "CoNnEcTrEqUeSt" & Indicator Then
            'Extract the client NickName from the message
            Nam = Mid(DATA, 21)
            'Add client's IP and Port to your collections
            Client.Add Key:=RmIP, Item:=RmPt
            Names.Add Key:=RmIP, Item:=Nam
            'Add client's IP to the listbox
            lName.AddItem RmIP
            Exit Sub
            'If a client wants to disconnect from the room:
        ElseIf DATA = Indicator & "CoNnEcTcAnCeL" & Indicator Then
            'Loop through listbox and find client's IP


            For X = 0 To lName.ListCount - 1
                lName.ListIndex = X
                RmEx = lName.Text
                'When found, remove IP from listbox
                If RmEx = RmIP Then lName.RemoveItem (X)
            Next


            'Remove client from your collections
            Client.Remove (RmIP)
            Names.Remove (RmIP)
            Exit Sub
        End If


        'If the message is text sent to the room:
    ElseIf DATA2 = "t" Then
        'Send text to clients
        Call SendOut(DATA)
    End If


End Sub



Private Sub Wsck_Error(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)


    'Error occured in winsock!
    MsgBox "An error occurred in winsock!"
    'Close connection
    Wsck.Close
End Sub



Sub SendOut(StringToSend As String)


    'Send a text message to all clients in collection/listbox
    'If an error occurs, ignore it and go on to the next command
    On Error Resume Next
    'Loop through all IP in listbox


    For X = 0 To lName.ListCount - 1
        'Select each IP
        lName.ListIndex = X
        'Set IP and Port to send to
        RmIP = lName.Text
        RmPt = Client(RmIP)
        Wsck.RemoteHost = RmIP
        Wsck.RemotePort = RmPt
        'Send text message
        Wsck.SendData "t" & StringToSend
    Next


   
    'Add the text message to your room
    tMain.Text = tMain.Text & StringToSend
    'Scroll to the bottom of the room
    tMain.SelStart = Len(tMain)
End Sub


'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'****************************************************************
'     *************************************************
'Name: Client and Server Chat Room (Client)
'Author: Matt Insler
'Written: 5/7/99
'Purpose: This program will allow more than a one on one direct c
'     onnection chat, like previous postings show.
' This will allow as many clients as have the client and the host
'     name or IP to chat by using a server to
' receive the messages and send them back out to all computers in
'     the collection. This is a good start
' for a mIrc style chat, or an AOL style chat, or any other type
'     of chat program. By adding a listbox
' to the client and making a procedure that will send all of the
'     names to the clients, and a procedure to
' receive and add the names, you can make a listbox showing who i
'     s in the room. Also, if you wish to make
' separate channels, or rooms, you can either run multiple versio
'     ns of the server on different ports, or
' you can add more winsock controls and have them all simultaneou
'     sly listening and running the server.
' If you happen to use my code as a stepping stool to a good chat
'     program or find any ways to make this program
' better, please send it to me at racobac@aol.com. Thanks.
'Input: Host IP or Computer Name, and a NickName, along with what
'     ever you wish to send to the room.
'Returns: What everyone who is in the room types back to you, alo
'     ng with your messages.
'Side Effects: None that I know of. If you find any, please email
'     me.
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'****************************************************************
'     *************************************************
'Create a new form and add four(4) text boxes, three(3) command b
'     uttons, and add the microsoft winsock control
'Change the name of the text boxes to tHost, tName, tMain, and tS
'     end, and name the command buttons cCon, cDis, cSnd
'Change the name of the winsock control to Wsck
'Change the caption of cCon to "Connect", cDis to "Disconnect", a
'     nd cSnd to "Send"
'Make tMain multiline = true, scrollbars = 2 - vertical, and lock
'     ed = true
'Make cDis and cSnd enabled = false
'
'Make cSnd Default = true
'Insert the following code
'Declarations:
Const Indicator = ":':"


Private Sub cCon_Click()


   
    'Connect button
    'Check if a Host Name or IP has been entered


    If Len(tHost) < 1 Then
        MsgBox ("Please make sure a Host has been entered!")
        'Put blinker in host text box
        tHost.SetFocus
        Exit Sub
        'Check if a NickName has been entered
    ElseIf Len(tName) < 1 Then
        MsgBox "You must enter a nickname first!"
        'Put blinker in NickName text box
        tName.SetFocus
        Exit Sub
    End If


   
    'If an error occurs, jump to Ending
    On Error GoTo Ending
    'Set the IP or Host Computer to connect to
    Wsck.RemoteHost = tHost.Text
    'Randomize a Port setting
    Wsck.LocalPort = Int((9999 * Rnd) + 1)
    'Set the Port to connect to
    Wsck.RemotePort = 2367
    'Connect!
    Wsck.Bind
    'Send system request to connect
    Wsck.SendData "s" & Indicator & "CoNnEcTrEqUeSt" & Indicator & tName.Text
    'Enable Send and Disconnect buttons, and disable Connect button a
    '     nd NickName text box
    cSnd.Enabled = True
    cDis.Enabled = True
    cCon.Enabled = False
    tName.Enabled = False
    'Put blinker in the Send text box
    tSend.SetFocus
    Exit Sub
    Ending:
    'Error handling
    MsgBox "You are not connected to the internet or the Host is not available.", , Form1.Caption
    'Click the Disconnect button
    cDis_Click
End Sub



Private Sub cDis_Click()


   
    'Disconnect button
    'If an error occurs, ignore it and go on to the next command
    On Error Resume Next
    'Send system message to disconnect from server
    Wsck.SendData "s" & Indicator & "CoNnEcTcAnCeL" & Indicator
    'Close connection
    Wsck.Close
    'Enable Connect button and NickName text box, and disable Send an
    '     d Disconnect buttons
    cCon.Enabled = True
    tName.Enabled = True
    cDis.Enabled = False
    cSnd.Enabled = False
    'Put blinker in NickName text box
    tName.SetFocus
End Sub



Private Sub cSnd_Click()


   
    'Send button
    Wsck.SendData "t" & tName.Text & ":" & vbTab & tSend.Text & Chr$(13) & Chr$(10)
    'Clear Send text box
    tSend.Text = ""
End Sub



Private Sub Form_Load()


    'We will be using UDP for this program because it does not establ
    '     ish a constant connection to another computer.
    'This will allow the server to keep "listening" for messages from
    '     other addresses on a network or the internet.
    Wsck.Protocol = sckUDPProtocol
    'Clear Main text box
    tMain.Text = ""
End Sub



Private Sub Form_Unload(Cancel As Integer)


    'End connection on Winsock
    Wsck.Close
    End
End Sub



Private Sub Wsck_DataArrival(ByVal bytesTotal As Long)


   
    'If an error occurs, ignore it and go on to the next command
    On Error Resume Next
    Dim Data As String
    Dim Data2 As String
    'Retreive message in string format
    Wsck.GetData Data, vbString
   
    'Get first letter of message
    Data2 = Left(Data, 1)
    'Get the rest of the message
    Data = Mid(Data, 2)
    'If the message is a system command:


    If Data2 = "s" Then
        'You can add your own system commands from the server to the clie
        '     nt here.
        'I have made one to throw out the client if I decide to.
        'If the message is text sent to the room:
    ElseIf Data2 = "t" Then
        'Add the text message to your room
        tMain.Text = tMain.Text & Data
        'Scroll to the bottom of the room
        tMain.SelStart = Len(tMain)
        Exit Sub
    End If


End Sub



Private Sub Wsck_Error(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)


    'Error occured in winsock!
    MsgBox "An error occurred in winsock!"
    'Close connection
    Wsck.Close
End Sub


0
 
LVL 1

Expert Comment

by:magoo2
ID: 1524530
poorboy...you can have 2 winsocks controls in your program...one set to listen for connections , and one that tries to connect


here is a dumb way to find their ip address:

you already know part of their ip address right? example 207.50.426.122....the 207.50.426. will always be the same

maybe use a timer and and a integer variable starting at 1  

in code , set the winsocks remote host to 207.50.426. & variable   ...thus making 207.50.426.1  


if it connects to your friend turn the timer off...if it doesnt , increase the variable by one and set the winsocks remote host to 207.50.426. & variable ...thus making 207.50.426.2

keep doing this 'till you are connected to your friend. is this slow? dang right it's slow!! you could make an array of 20 winsocks and load em when u wanna connect...make them start in increments of 10 , and make each one increase their variable by one every time the timer event fires.when ya connect to friend , unload all the winsocks that arent connected and turn off the timer.


 is this slow? its 20 X faster than using just one winsock control...is this efficient? you'd have to ask somebody smarter than me...does this work? if they are connected to the net and have their program on , yes it does work

hope this dont confuse you as much as it has me
0
 

Expert Comment

by:flavio_sr
ID: 1524531
magoo2 had a good idea, but if the IP is from 207.50.426.1 to 207.50.426.200?

you may try using a web server (like Geocities, Hypermart, etc) as the source of information, make de app put the IP into a text file and send it to a web server (may be with Internet Transfer Control), and the other app gets it from the web server, opens the text file and sets the remotehost to that IP. this works fine with me.

about the server/client program, you can make an app that can be both at the same time, just set the winsock to listen when you want to answer calls, or close de winsock (to reset it), set the localport to 0, and make it connect to the other app.

you may test the program offline, make the both app and set "localhost" as the remote host, and run it.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes…
Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

671 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question