Chat Server in VB.net
By: Issac in VB.net Tutorials on 2009-02-22
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.
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
Add Comment
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
- Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
- Aside from the data entered into these form fields, other stored data about your comment will include:
- Your IP address (not displayed)
- The time/date of your submission (displayed)
- Your email address will not be shared. It is collected for only two reasons:
- Administrative purposes, should a need to contact you arise.
- To inform you of new comments, should you subscribe to receive notifications.
- A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
- Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
- You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
- You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
- The administrator has the right to edit, move or remove any comment for any reason and without notice.
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
- Data Science
- Android
- React Native
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Changes in Controls from VB6 to VB.net
Unstructured Exception Handling in VB.net
Structured Exception Handling in VB.net
Creating Sub Procedures 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
Throwing an Exception in VB.net
Comments