Create Chat Group Using VB.Net
Hello friends, in this post I will discuss about how to create a simple chat group app that is connected on the same network, using Visual Studio IDE. Such an application is certainly very useful to exchange information, for example if two employees who want to communicate but the first employee is on the 1st floor while the other employees are on the 2nd floor. That's one example of the benefits of this kind of application and of course there are still benefits other.
Now open and create a new project in Visual Studio, then design a form as server more or less as shown below
NOTES :
Componen Form Server :
Componen Form Server :
- 4 Label
- 2 TextBox
- 2 RichTextBox
- 1 Button
- 1 PictureBox
Next, create a new project again and design the form as a client more or less like in the picture below
NOTES :
Componen Form Client :
Now, we go back to the project form server, then create a module and name it CPcontrolClass and enter the following codeComponen Form Client :
- 2 Label
- 3 TextBox
- 2 Button
- 1 RichTextBox
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.IO
Public Class CPcontrolClass
Public Event MessageReceived(ByVal sender As CPcontrolClass, ByVal Data As String)
Public serverIP As IPAddress = IPAddress.Parse("127.0.0.1")
Public serverPORT As Integer = 8080
Public server As TcpListener
Private comThread As Thread
Public isListening As Boolean = True
Private client As TcpClient
Private clientData As StreamReader
Public Sub New()
server = New TcpListener(serverIP, serverPORT)
server.Start()
comThread = New Thread(New ThreadStart(AddressOf Listening))
comThread.Start()
End Sub
Public Sub ipnya()
Dim addrs As IPAddress
Dim x As Byte = 0
Do
addrs = Dns.GetHostEntry(Dns.GetHostName).AddressList(x)
x += 1
Loop Until (addrs.AddressFamily = AddressFamily.InterNetwork)
End Sub
Private Sub Listening()
Do Until isListening = False
If server.Pending = True Then
client = server.AcceptTcpClient
clientData = New StreamReader(client.GetStream)
End If
Try
RaiseEvent MessageReceived(Me, clientData.ReadLine)
My.Computer.Audio.PlaySystemSound(Media.SystemSounds.Beep)
Catch ex As Exception
End Try
Thread.Sleep(100)
Loop
End Sub
End Class
NOTES :
127.0.0.1 is the local IP Address, if you want to use with a different device, please replace it with your device's ip address.
127.0.0.1 is the local IP Address, if you want to use with a different device, please replace it with your device's ip address.
After that, import some of the required libraries on the server form
Imports System.Net
Imports System.Net.Sockets
Imports System.Runtime.InteropServices
Imports System.Threading
Imports System.IO
Public Class Form1
End Class
Then, declare some global variables
Public Class Form1
Private server As CPcontrolClass
Dim log As String
Dim ipserver As IPAddress
Private TCPListener As TcpListener
Private clientCollection As New Hashtable()
Private usernameCollection As New Hashtable()
Private Shared connectID As Long = 0
Private serverThread As Thread
Public Delegate Sub updateListboxDelegate(ByVal str As String)
Dim clientThread As System.Threading.Thread
Dim client As New TcpClient
Dim reader As BinaryReader
Dim writer As BinaryWriter
Dim message As String
Dim username As String
Delegate Sub updateMessageDelegate(ByVal message As String)
Delegate Sub updateUserDelegate(ByVal message As String)
End Class
Then, create some of the following functions
Public Structure ClientData
Public structSocket As TcpClient
Public structThread As Thread
Public structReader As BinaryReader
Public structWriter As BinaryWriter
End Structure
Sub updateMessageWork(ByVal message As String)
RichTextBox1.AppendText(message + vbNewLine)
End Sub
Sub updateMessage(ByVal message As String)
If RichTextBox1.InvokeRequired Then
Invoke(New updateMessageDelegate(AddressOf updateMessageWork), message)
Else
RichTextBox1.AppendText(message + vbNewLine)
End If
End Sub
Sub updateUserWork(ByVal message As String)
Dim userlist() As String = Split(message, Chr(13))
Dim i As Integer
lbUser.Items.Clear()
For i = 0 To userlist.Length - 1
lbUser.Items.Add(userlist(i))
Next
End Sub
Sub updateUser(ByVal message As String)
If lbUser.InvokeRequired Then
Invoke(New updateUserDelegate(AddressOf updateUserWork), message)
End If
End Sub
Public Sub readSocket()
Dim realId As Long = connectID
Dim CData As New ClientData
CData = CType(clientCollection(realId), ClientData)
Dim message As String
Dim found As Boolean = False
While True
If CData.structSocket.Connected Then
Try
message = CData.structReader.ReadString()
If message.Substring(0, 3) = "MES" Then
For Each Client As ClientData In clientCollection.Values
If Client.structSocket.Connected Then
Client.structWriter.Write(message)
End If
Next
ElseIf message.Substring(0, 3) = "USR" Then
For Each user As String In usernameCollection.Values()
If user = message.Substring(4) Then
found = True
End If
Next
If found = True Then
message = "err"
For Each Client As ClientData In clientCollection.Values()
If Client.structSocket.Connected Then
Client.structWriter.Write(message)
Exit For
End If
Next
Try
Dim client As ClientData = CType(clientCollection(realId), ClientData)
client.structThread.Abort()
Catch e As Exception
SyncLock Me
clientCollection.Remove(realId)
usernameCollection.Remove(realId)
End SyncLock
End Try
Else
usernameCollection.Add(realId, message.Substring(4))
Dim userlist As String = ""
For Each user As String In usernameCollection.Values()
userlist = userlist & user & Chr(13)
Next
For Each Client As ClientData In clientCollection.Values()
If Client.structSocket.Connected Then
Client.structWriter.Write("USR " & userlist)
End If
Next
End If
ElseIf message.Substring(0, 3) = "DIS" Then
usernameCollection.Remove(realId)
Dim userlist As String = ""
For Each user As String In usernameCollection.Values()
userlist = userlist & user & Chr(13)
Next
For Each Client As ClientData In clientCollection.Values()
If Client.structSocket.Connected Then
Client.structWriter.Write("USR " & userlist)
End If
Next
End If
Catch e As Exception
Exit While
End Try
End If
End While
CloseTheThread(realId)
End Sub
Private Sub CloseTheThread(ByVal realId As Long)
Try
Dim client As ClientData = CType(clientCollection(realId), ClientData)
client.structThread.Abort()
Catch e As Exception
SyncLock Me
clientCollection.Remove(realId)
usernameCollection.Remove(realId)
End SyncLock
End Try
End Sub
Private Sub OnlineReceived(ByVal sender As CPcontrolClass, ByVal Data As String)
End Sub
Public Sub readSocketClient()
While True
Try
message = reader.ReadString()
If message.Substring(0, 3) = "MES" Then
updateMessage(message.Substring(4))
ElseIf message.Substring(0, 3) = "USR" Then
updateUser(message.Substring(4))
ElseIf message.Substring(0, 3) = "DIS" Then
updateUser(message.Substring(4))
End If
If message = "err" Then
Exit Sub
End If
Catch e As Exception
Exit While
End Try
End While
End Sub
Public Sub writeSocket(ByVal message As String)
If client.Connected Then
writer.Write(message)
End If
End Sub
Sub startConnect()
Try
client = New TcpClient()
client.Connect(ipserver, 8888)
reader = New BinaryReader(client.GetStream())
writer = New BinaryWriter(client.GetStream())
writer.Write("USR " + TextBox1.Text)
username = TextBox1.Text
clientThread = New System.Threading.Thread(AddressOf readSocketClient)
clientThread.Start()
server = New CPcontrolClass
AddHandler server.MessageReceived, AddressOf OnlineReceived
RichTextBox1.Visible = True
lbUser.Visible = True
Catch ex As Exception
Exit Sub
End Try
End Sub
Public Sub New()
InitializeComponent()
End Sub
Public Sub waitingForClient()
Dim CData As New ClientData
While True
CData.structSocket = TCPListener.AcceptTcpClient
Interlocked.Increment(connectID)
CData.structThread = New Thread(AddressOf readSocket)
CData.structReader = New BinaryReader(CData.structSocket.GetStream())
CData.structWriter = New BinaryWriter(CData.structSocket.GetStream())
SyncLock Me
clientCollection.Add(connectID, CData)
End SyncLock
CData.structThread.Start()
End While
End Sub
Then, double-click Button1 and enter the following code
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text = "" Or TextBox3.Text = "" Then
MsgBox("please complete the field", MsgBoxStyle.Exclamation)
Else
Dim addr As IPAddress = IPAddress.Parse(TextBox3.Text)
ipserver = addr
TCPListener = New TcpListener(addr, 8888)
TCPListener.Start()
serverThread = New Thread(AddressOf waitingForClient)
serverThread.Start()
startConnect()
MsgBox("Connection Successful As " + TextBox1.Text, MsgBoxStyle.Information)
TextBox1.Clear()
TextBox3.Clear()
End If
End Sub
Next, enter the following code in the Form_Closing event
Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
writeSocket("DIS:")
If Not (clientThread Is Nothing) Then
If clientThread.IsAlive Then clientThread.Abort()
End If
If Not (reader Is Nothing) Then
reader.Close()
End If
If Not (writer Is Nothing) Then
writer.Close()
End If
If Not (client Is Nothing) Then
client.Close()
End If
Me.Dispose()
End Sub
Now, we have finished on the server part, now we move on client project. Same as server, create a module and name it TCPcontroller, then enter the following code
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Public Class TCPcontroller
Public client As TcpClient
Public clientData As StreamWriter
Public Sub New(ByVal Host As String, ByVal Port As Integer)
On Error Resume Next
client = New TcpClient(Host, Port)
clientData = New StreamWriter(client.GetStream)
End Sub
Public Sub send(ByVal Data As String)
On Error Resume Next
clientData.Write(Data & vbCrLf)
clientData.Flush()
End Sub
End Class
Next, go to the form section, then import some of the required libraries
Imports System.Drawing.Text
Imports System.Net.Sockets
Imports System.Text
Imports System.IO
Imports System.Net
Public Class Form1
End Class
Then, declare the following global variables
Public Class Form1
Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As
String, ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer
Private clientnya As TCPcontroller
Dim FileName As String
Dim pfc As New PrivateFontCollection()
Dim status As Byte
Dim clientThread As System.Threading.Thread
Dim client As New TcpClient
Dim screen As Screen
Dim reader As BinaryReader
Dim writer As BinaryWriter
Dim message As String
Dim username As String
Delegate Sub updateMessageDelegate(ByVal message As String)
End Class
Then, make some of the following functions
Sub updateMessageWork(ByVal message As String)
RichTextBox1.AppendText(message + vbNewLine)
End Sub
Sub updateMessage(ByVal message As String)
If RichTextBox1.InvokeRequired Then
Invoke(New updateMessageDelegate(AddressOf updateMessageWork), message)
Else
RichTextBox1.AppendText(message + vbNewLine)
End If
End Sub
Sub startConnect()
Try
client = New TcpClient()
client.Connect(IPAddress.Parse(TextBox3.Text), 8888)
reader = New BinaryReader(client.GetStream())
writer = New BinaryWriter(client.GetStream())
writer.Write("USR " & TextBox2.Text)
username = TextBox2.Text
clientThread = New System.Threading.Thread(AddressOf readSocketClient)
clientThread.Start()
Catch ex As Exception
Exit Sub
End Try
End Sub
Public Sub readSocketClient()
While True
Try
message = reader.ReadString()
If message.Substring(0, 3) = "MES" Then
updateMessage(message.Substring(4))
End If
If message = "err" Then
MsgBox("Problem Connection", MsgBoxStyle.Information, "Information")
message = reader.ReadString()
End
End If
Catch e As Exception
Exit While
End Try
End While
End Sub
Public Sub writeSocket(ByVal message As String)
Try
If client.Connected Then
writer.Write(message)
End If
Catch ex As Exception
Exit Sub
End Try
End Sub
Next, double-click the Sign In Button and enter the following code
Private Sub ButtonSignIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSignIn.Click If ButtonSignIn.Text = "SIGN IN" Then If TextBox2.Text = "" Or TextBox3.Text = "" Then MsgBox("please complete all fields", MsgBoxStyle.Exclamation) Else clientnya = New TCPcontroller(TextBox3.Text, 8080) startConnect() ButtonSignIn.Text = "SIGN OUT" ButtonSignIn.FlatAppearance.MouseOverBackColor = Color.Red MsgBox("You Are Connected As " + TextBox2.Text, MsgBoxStyle.Information) TextBox2.Clear() TextBox3.Clear() End If Else writeSocket("DIS:") If Not (clientThread Is Nothing) Then If clientThread.IsAlive Then clientThread.Abort() End If If Not (reader Is Nothing) Then reader.Close() End If If Not (writer Is Nothing) Then writer.Close() End If If Not (client Is Nothing) Then client.Close() End If MsgBox("You Sign Out", MsgBoxStyle.Information) ButtonSignIn.Text = "SIGN IN" ButtonSignIn.FlatAppearance.MouseOverBackColor = Color.Green End If End Sub
Next, double-click the send button and enter the following code
Private Sub ButtonSent_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSent.Click
If ButtonSent.Text = "SIGN IN" Then
MsgBox("You Must Sign In First", MessageBoxIcon.Exclamation)
Else
If TextBox1.Text = "" Then
MsgBox("Message Can not Empty.", MessageBoxIcon.Exclamation)
Else
writeSocket("MES:" & username & " : " & TextBox1.Text)
TextBox1.Text = ""
TextBox1.Focus()
End If
End If
End Sub
and finally, enter the following code in the Form_Closing event
Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
writeSocket("DIS:")
If Not (clientThread Is Nothing) Then
If clientThread.IsAlive Then clientThread.Abort()
End If
If Not (reader Is Nothing) Then
reader.Close()
End If
If Not (writer Is Nothing) Then
writer.Close()
End If
If Not (client Is Nothing) Then
client.Close()
End If
Dispose()
End Sub
Up here, the program is ready to run using one device. If you want to use multiple devices, do not forget to change the IP Address of the device you want to use