Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleUse winsock to make a simple chat program
DescriptionThis example shows how to use winsock to make a simple chat program in Visual Basic 6.
Keywordswinsock, chat, IPC
CategoriesSoftware Engineering
 
Thanks to rskeleton@yahoo.com.

To run the program, compile the executable and then run two instances of it. In one, click "Listen" and then in the other click "Connect." Then you can send messages between them.

The Listen button sets the socket to 554 and calls its Listen method.

 
Private Sub cmdListen_Click()
    ' set localport for listening ( you can change it
    ' whatever you want )
    Sck.LocalPort = 554
    Sck.Listen ' listen for others to connect you
    UpdateState
End Sub
 
The Connect button uses its socket to connect to port 554 on the local computer.

When the socket object receives a connection request, it accepts.

 
Private Sub cmdConnect_Click()
    Sck.Connect "127.0.0.1", 554 ' connect to server
        ' listening on port 554
    UpdateState
End Sub

Private Sub sck_ConnectionRequest(ByVal requestID As Long)
    If Sck.State <> sckClosed Then Sck.Close ' if not
        ' closed the connection close it
    Sck.Accept requestID ' accept the requestid
End Sub
 
The Send button adds the user's nickname entered in txtNick to the message and uses the socket's SendData method to send the message. It then displays the message locally.

When the socket receives new data, it adds it to its display.

 
Private Sub cmdSend_Click()
Dim DataWillBeSent As String

    DataWillBeSent = txtNick.Text & " said, '" & _
        txtOut.Text & "'" ' add your nick to the data will
        ' sent
    Sck.SendData DataWillBeSent ' sent data
    If txtin.Text = "" Then
        txtin.Text = DataWillBeSent
    Else
        txtin.Text = txtin.Text & vbCrLf & DataWillBeSent
    End If
    txtOut.Text = "" ' clear the textbox
    UpdateState
End Sub

Private Sub Sck_DataArrival(ByVal bytesTotal As Long)
    Dim IncomeData As String
    Sck.GetData IncomeData ' get data
    If txtin.Text = "" Then
        txtin.Text = IncomeData
    Else
        txtin.Text = txtin.Text & vbCrLf & IncomeData '
            ' append the data to the textbox
    End If
End Sub
 
Finally, the Close button calls the socket's Close method.
 
Private Sub cmdClose_Click()
    Sck.Close ' close connection
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated