Chat Server in VB.net

By: Issac Emailed: 1729 times Printed: 2338 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

A chat server program is one which listens to the connection request from clients and broadcasts the msg to all clients that are connected to it at that instant.

The VB.NET Multithreaded Chat Server Program has two sections.

  • Chat Server
  • Chat Client

Chat server keeps listening to PORT 8888 for any request from clients, once a request is received it adds the name of the client into a client list maintained (in this code it is a Hash table) and then creates a new thread for communication with server. When the Server gets a message from a client, it selects all the Clients from clientsList and sends the message to all Clients (ie we can say Broadcast) in the clientsList. So each Client can see the message each other and they can communicate through Chat Server.

The client list we implemented here in a HashTable. The clientsList stores the Client Name (ie the first message from Client) and an instance of the Client Socket.

When a Chat Client connected to Server, the Server creates a new Thread for communication. Here we implement a Class handleClient for handling Client as a separate Thread. The Class handleClient has a function doChat () is handling the communication between the Server side Client Socket and the incoming Client Socket.

When Server gets a message from any of the currently connected Chat Client, the Server Broadcast the message to all Clients using broadcast method for sending messages to all Clients.

vb.net_chat_server.JPG

Create a new VB.NET Console based application and put the following source code into the Project..

Imports System.Net.Sockets
Imports System.Text
Module Module1
    Dim clientsList As New Hashtable
    Sub Main()
        Dim serverSocket As New TcpListener(8888)
        Dim clientSocket As TcpClient
        Dim counter As Integer

        serverSocket.Start()
        msg("Chat Server Started ....")
        counter = 0

        While (True)
            counter += 1
            clientSocket = serverSocket.AcceptTcpClient()

            Dim bytesFrom(10024) As Byte
            Dim dataFromClient As String

            Dim networkStream As NetworkStream = _
            clientSocket.GetStream()
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
            dataFromClient = _
            dataFromClient.Substring(0, dataFromClient.IndexOf("$"))

            clientsList(dataFromClient) = clientSocket

            broadcast(dataFromClient + " Joined ", dataFromClient, False)

            msg(dataFromClient + " Joined chat room ")
            Dim client As New handleClinet
            client.startClient(clientSocket, dataFromClient, clientsList)
        End While

        clientSocket.Close()
        serverSocket.Stop()
        msg("exit")
        Console.ReadLine()
    End Sub

    Sub msg(ByVal mesg As String)
        mesg.Trim()
        Console.WriteLine(" >> " + mesg)
    End Sub
    Private Sub broadcast(ByVal msg As String, _
    ByVal uName As String, ByVal flag As Boolean)
        Dim Item As DictionaryEntry
        For Each Item In clientsList
            Dim broadcastSocket As TcpClient
            broadcastSocket = CType(Item.Value, TcpClient)
            Dim broadcastStream As NetworkStream = _
                    broadcastSocket.GetStream()
            Dim broadcastBytes As [Byte]()

If flag = True Then
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg)
Else
broadcastBytes = Encoding.ASCII.GetBytes(msg)
End If

        broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length)
            broadcastStream.Flush()
        Next
    End Sub

    Public Class handleClinet
        Dim clientSocket As TcpClient
        Dim clNo As String
        Dim clientsList As Hashtable

        Public Sub startClient(ByVal inClientSocket As TcpClient, _
        ByVal clineNo As String, ByVal cList As Hashtable)
            Me.clientSocket = inClientSocket
            Me.clNo = clineNo
            Me.clientsList = cList
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat)
            ctThread.Start()
        End Sub

        Private Sub doChat()
            'Dim infiniteCounter As Integer
            Dim requestCount As Integer
            Dim bytesFrom(10024) As Byte
            Dim dataFromClient As String
            Dim sendBytes As [Byte]()
            Dim serverResponse As String
            Dim rCount As String
            requestCount = 0

            While (True)
                Try
                    requestCount = requestCount + 1
                    Dim networkStream As NetworkStream = _
                            clientSocket.GetStream()
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
                    dataFromClient = _
            dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
        msg("From client - " + clNo + " : " + dataFromClient)
                    rCount = Convert.ToString(requestCount)

                    broadcast(dataFromClient, clNo, True)
                Catch ex As Exception
                    MsgBox(ex.ToString)
                End Try
            End While
        End Sub

    End Class
End Module



VB.net Home | All VB.net Tutorials | Latest VB.net Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(5)


1. View Comment

i get this msg when one of the clients close there chat window there should be a disconnect code to stop this error and the msg is :

serverStream.Read(inStream, 0, buffSize)

Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.


reply as soon as possible because im working on a system administrator for networks and im using same code but different design .

Zero Code


View Tutorial          By: Zero Code at 2009-07-16 14:05:14
2. View Comment

hey. How would i get the ClientLists displayed in a textbox in the client?? Thanks

View Tutorial          By: andrew at 2009-07-24 14:10:24
3. View Comment

sir i m getting chat server started bt how a client can join

View Tutorial          By: ashu at 2010-11-02 08:13:00
4. View Comment

@Zero Code

@
Catch ex As Exception
'add this
clientsList.Clear()
MsgBox(ex.ToString)
End Try


View Tutorial          By: Chitz at 2011-12-24 19:50:45
5. View Comment

this code should be commented I mean a lot of comments

View Tutorial          By: mmmm at 2012-03-31 00:44:41

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Issac
Save/Write/Read image file from/to a database using Java program
How to modify the objects using java classes
Java program for Cloning
Java program for changeable wrapper class
A tutorial on Chat Server and Chat Client in VB.net
Chat Server in VB.net
Chat client in VB.net
How to open and read an XML file in VB.net
How to create an XML file in VB.net
XML and VB.net
How to create an XML file in VB.NET using Dataset
Multi Threaded Client Socket Programming in VB.net
Multi Threaded Server Socket Programming in VB.net
Multi threaded Socket Programming in VB.net
Client Socket Program sample in VB.net

More Tutorials in VB.net
Scope in VB.net
Unstructured Exception Handling in VB.net
Structured Exception Handling in VB.net
Creating Sub Procedures in VB.net
Creating Functions in VB.net
Passing a Variable Number of Arguments to Procedures in VB.net
Specifying Optional Arguments with default values in Procedures in VB.net
Preserving a Variable's Values between Procedure Calls in VB.net
Procedure Delegates in VB.net
Properties in VB.net
Understanding Scope in VB.net
Using Resume Next and Resume Line in VB.net
Using On Error GoTo 0 in VB.net
Getting an Exception's Number and Description in VB.net
Raising an Exception Intentionally in VB.net

More Latest News
Most Viewed Articles (in VB.net )
How to export from database to excel using VB.net
Preserving a Variable's Values between Procedure Calls in VB.net
Using On Error GoTo 0 in VB.net
The Select Case statement in VB.net
Assemblies, Solutions and Projects in VB .NET
The Option and Imports Statements in VB .NET
Sub Procedures and Functions in VB.net
To read the entire worksheet in an Excel workbook through VB.net Code
Read Data from Excel using OLEDB in VB.NET 2005
Creating Tree Views in Code using VB.net
Understanding Scope in VB.net
Raising an Exception Intentionally in VB.net
“Using If with And” and Comparing two integers using If
Debug and Release Versions in .NET
File Extensions Used in VB .NET
Most Emailed Articles (in VB.net)
ArrayList data structure in VB.net
The Option and Imports Statements in VB .NET
Stack data structure in VB.net
Queue data structure in VB.net
String Insert, index off & format in VB.net
OleDbDataAdapter class in VB.net
Creating Menus in Code using VB.net
Creating Context Menus in Code using VB.net
Creating a Windows Service Installer in VB.net
Creating Functions in VB.net
Preserving a Variable's Values between Procedure Calls in VB.net
Using On Error GoTo 0 in VB.net
“Using If with And” and Comparing two integers using If
Nested If and Single line if statement
The Select Case statement in VB.net