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
How do I add a voice chat now?
ReplyDeletePositive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. no registration cams
ReplyDeleteNot Working On Many Pc Can Help Then Do So
ReplyDeleteyou use a wonderful blog here! want to earn some invite posts in my small weblog? qqlive.download
ReplyDeletePrince of Persia is the best, i really like the lead actor and also the princess, the princess is very pretty.. chatavenue
ReplyDeletePositive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. studio videochat
ReplyDeleteIt should be noted that whilst ordering papers for sale at paper writing service, you can get unkind attitude. In case you feel that the bureau is trying to cheat you, don't buy term paper from it. wazirx referral code
ReplyDeletebuy twitch followers The reign of the Xbox is almost over. As of late the PS3 has been looking better and better. Looks like 2008 will be the year of the PlayStation. PlayStation 3 has many big name titles coming out this year and if the all games from the list are all actually released this year, all we can say is WOW. Note: The following list in no way represents the entire list of exclusive titles for each console. However, it gives us a pretty good idea of the games rumored to be released this year.
ReplyDeletehttps://www.visualaidscentre.com/service/eyes-specialist-delhi/ Thunderstone is a deck-building game by Mike Elliott, published in 2009, one year after Dominion hit the market, creating a frenzy with the introduction of a hot combination of game mechanics: deck building and card drafting. In games using these mechanics, players choose cards from a common pool layed out on the table, and try to gradually built the best deck of cards with which they will acquire the most victory points. The theme of such games may differ but the main idea remains the same. With this review we will look at 2 games, the original Thunderstone released in 2009 and the new Thunderstone Advance, which is a new improved implementation of the original game.
ReplyDeletehttps://www.buyyoutubesubscribers.in/2022/01/15/top-10-most-viewed-videos-youtube-24-hours/ The social media platform is getting bigger each day. On several blogs, you see many people talking about how they made money on the different social media platforms including YouTube. Though most people would think that it is impossible, there are ways on how to make money from YouTube.
ReplyDeletehttps://dynamichealthstaff.com/jobs-in-dubai-for-nurses SEO (Search Engine Optimization) has undergone a sea of change since the last year. Nowadays, one would not feel comfortable to put up a crappy website and get a large number of low quality backlinks pointing back to the same. The increasing complexity of SEO can be gauged by the fact that search engines are looking into following factors before deciding whether or not to reward high ranks to websites.
ReplyDeletehttps://hostinglelo.in With the popularity of the internet growing over the past few decades, people are finding new and innovative ways in order to use this technology. One of the most popular methods to using the internet is to make money and YouTube is gaining as one of the sites that people are using in order to make this money online. If you are interested in learning how to make money online with YouTube, look at some of the suggestions below.
ReplyDeleteI am very happy to discover your post as it will become on top in my collection of favorite blogs to visit. omegle random chat alternative
ReplyDeleteIf you need help with your account or just have any other questions about QuickBooks, all you have to do is dial Quickbooks Customer Support Phone Number+1 888-210-4052.
ReplyDeleteYour blogs are great. Are you also searching for assignment help services? We are the best solution for you. We are best known for delivering assignment help services to students without having to break the bank. WhatsApp us: +91-9872003804, +61-413228507.
ReplyDeleteThis is the post I was looking for. I am very happy to read this article. If you have time, please come to my site Job Alert Vacancy and share your thoughts. Have a nice day.
ReplyDeleteTo get instant support for QuickBooks problems, dial QuickBooks Customer Support Phone Number +1 866-669-5068. Our team makes sure to provide you with the best-in-class technical service for QuickBooks at a reasonable rate.
ReplyDeleteIt is savvy to Get prepared in India. The Cost of Commercial Pilot Training Program in India From our companion flying college stages is 30-35 lacs. CEA Aviation offers a significant assortment of airspaces for training, going from out of control touchdown strips to occupied agency air terminals, which subsequently gives the hopeful pilots a real involvement with searching after complex radiotelephony and device method techniques at an affordable price.
ReplyDeleteFocusing in on, investigating, enhancement, and talking. Cambridge English Academy gives genuine and professional IELTS snippets of records to help you with shutting your certainly reading collecting. Go to IELTS coaching in Delhi to make approximately the IELTS take a look at the plan. IELTS is an English language check that is firmly taken by people that need to install or work in a town where English is the high-quality language of correspondence. The maximum hanging fashionable spots in which IELTS is applied for labour force licences are the UK, Australia, New Zealand, the USA, and Canada.
ReplyDeleteThanks for sharing your blog. In this Blog you have given an Informative Information which are very important for users.
ReplyDeleteShared Hosting Providers
Dedicated Servers Unmanagedr
Unmanaged Dedicated Server Hosting
Game Server Rental
The call for the pilot licence holders is all over again developing more potent and the aspirants can now in fact see their dreams flying to fact. CEA Aviation, with its specialisation in aviation and considerable diploma in national and international first rate flight school in delhi is amongst a particular few in India and is proving to be an outstanding launch pad for pilots with its International institutions for the tremendous feasible Pilot training.
ReplyDeleteทุกครั้งที่มารู้จักและทดลองเล่นกับเรา
ReplyDeleteเราอยากจะพูดถึงเกมสล็อตแจ็คพอตง่าย ๆ ยอดนิยมที่กลับมาได้รับความนิยมอีกครั้ง ตัวอย่างเช่น หนังสือลึกลับของอียิปต์ Caishen Wins, Genesha Fortune และ Rise of Apollo ทั้งหมดนี้คือเกมสล็อตออนไลน์แจ็คพอตยอดนิยม ของปี 2564 นอกจากนั้น แจ็คพอตจะแตกง่ายและยังเล่นง่ายอีกด้วย https://winner1668.com/win555/
การค้นพบเหล่านี้ควรได้รับการพิจารณาสำหรับแผนการจัดเตรียมงานฟุตซอลตามสถานการณ์เฉพาะ (กลุ่ม ผู้เล่น … ) และเวลาและฤดูกาล เนื่องจากปัจจัยเหล่านี้ช่วยให้เกิดความก้าวหน้าของปัจจัยที่แสดงโดยการเพิ่มเวลาในการเตรียมลูกบอล https://winner1668.com/joker-gaming-777/
ReplyDeleteWeed online kaufen, Marihuana online bestellen, Weed online kaufen in Deutschland
ReplyDeleteCannabis online bestellen bei Geasherr.com ist schnell und einfach
Sie können ganz einfach professionell angebautes Weed in unserem Online-Weedshop kaufen und es sich nach Hause oder an eine beliebige Adresse liefern lassen.
Wählen Sie Ihr Cannabis aus und legen Sie es in Ihren Warenkorb. Wir verschicken unser Marihuana diskret mit den besten Express-Versandmethoden per Post oder DHL.
https://grasherr.com/
UFA SLOT เว็บพนันอันดับ 1 เดิมพันขั้นต่ำ10บาท
ReplyDeleteUFA SLOT หรือที่หลายๆท่านรู้จักกันดีอย่าง ยูฟ่าสล็อต เว็บเดิมพันสล็อตออนไลน์ครบวงจร UFA CASINO ที่ได้รับรางวัลการันตีว่าเป็นเว็บเล่นยูฟ่าสล็อตออนไลน์ที่ดีที่สุดซึ่งทางยูฟ่าสล็อตออนไลน์บนมือถือของเรานั้นได้มีการรวบรวมเกมสล็อตออนไลน์ รูปแบบหลากหลายประเภทให้บริการบนเว็บยูฟ่าสล็อต เพื่อเอาใจเหล่านักลงทุนเดิมพันซึ่งเกมสล็อตแต่ละเกมนั้นก็มีรูปแบบที่น่าสนใจให้ท่านนั้นเลือกเล่นมากกว่า 500 รูปแบบเล่นได้ไม่มีซ้ำ หากท่านใดสนใจทางเราขอแนะนำเว็บUFASLOTให้ทุกท่านได้ลองใช้บริการเดิมพันยูฟ่าสล็อตขั้นต่ำ10บาทพร้อมรูปแบบเว็บไซต์ที่ดีที่สุด https://casinopro.info/ufa-slot/
Stealthfakies offers Australian, UK, New Zealand, US , . Either you need a State’s ID or a Driver licence, we will provide you with fake ID cards that would reflect under UV light and other light testing systems. Our IDs have the correct OVI holograms that produce the right reflection, details, and shadows under UV blacklight, laser perforation, and so on. https://stealthdocuments.com/index.php/australian-fake-id/
ReplyDeleteslotxo ล็อกอิน Slotxo สล็อตออนไลน์ แจกเครดิตฟรีทุกวัน โบนัส 50% คลิกสมัคร!
ReplyDeleteslotxo ล็อกอิน SLOTXO ถ้ารู้จักกับตัวเกมสล็อตต้องหลงรัก เพราะเป็นเกมหนึ่งที่อยู่ในวงการสล็อตออนไลน์ และมีผู้เล่นมากมาย
https://winner1668.com/slotxo-login/
Hi, I find reading this article a joy. It is extremely helpful and interesting and very much looking forward to reading more of your work.. singles near me
ReplyDelete