Full Source Code
Create new Class for Read All Client (ClassForClient.vb)
Leave the Form1.vb and create a new class "ClassForClient.vb" and write all source code below :
Imports System.Net.Sockets
Imports System.IO
Public Class ClassforClient
Public Event getMessage(ByVal str As String)
Public Event clientLogout(ByVal client As ClassforClient)
Private sendMessage As StreamWriter
Private listClient As TcpClient
Sub New(ByVal forClient As TcpClient)
listClient = forClient
listClient.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf ReadAllClient, Nothing)
End Sub
Private Sub ReadAllClient()
Try
RaiseEvent getMessage(New StreamReader(listClient.GetStream).ReadLine)
listClient.GetStream.BeginRead(New Byte() {0}, 0, 0, New AsyncCallback(AddressOf ReadAllClient), Nothing)
Catch ex As Exception
RaiseEvent clientLogout(Me)
End Try
End Sub
Public Sub Send(ByVal Messsage As String)
sendMessage = New StreamWriter(listClient.GetStream)
sendMessage.WriteLine(Messsage)
sendMessage.Flush()
End Sub
End Class
Back to the Form1.vb
Source code TCP/IP Server (Form1.vb)
Just write all source code below:
Imports System.Net
Imports System.IO
Imports System.Net.Sockets
Public Class Form1
Dim Listning As TcpListener
Dim Allclient As TcpClient
Dim clientList As New List(Of ClassforClient)
Dim pReader As StreamReader
Dim pClient As ClassforClient
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Listning = New TcpListener(IPAddress.Any, 3818)
Listning.Start()
UpdateList("Server Starting", False)
Listning.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listning)
End Sub
' create a delegate
Delegate Sub _cUpdate(ByVal str As String, ByVal relay As Boolean)
Sub UpdateList(ByVal str As String, ByVal relay As Boolean)
On Error Resume Next
If InvokeRequired Then
Invoke(New _cUpdate(AddressOf UpdateList), str, relay)
Else
TextBox1.AppendText(str & vbNewLine)
' if relay we will send a string
If relay Then send(str)
End If
End Sub
Sub send(ByVal str As String)
For x As Integer = 0 To clientList.Count - 1
Try
clientList(x).Send(str)
Catch ex As Exception
clientList.RemoveAt(x)
End Try
Next
End Sub
Sub AcceptClient(ByVal ar As IAsyncResult)
pClient = New ClassforClient(Listning.EndAcceptTcpClient(ar))
AddHandler(pClient.getMessage), AddressOf MessageReceived
AddHandler(pClient.clientLogout), AddressOf ClientExited
clientList.Add(pClient)
UpdateList("New Client Joined!", True)
Listning.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listning)
End Sub
Sub MessageReceived(ByVal str As String)
UpdateList(str, True)
End Sub
Sub ClientExited(ByVal client As ClassforClient)
clientList.Remove(client)
UpdateList("Client Exited!", True)
End Sub
Private Sub TextBox2_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox2.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
UpdateList("Server says : " & TextBox2.Text, True)
TextBox2.Clear()
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
UpdateList("Server says : " & TextBox2.Text, True)
TextBox2.Clear()
End Sub
End Class
Yes, we have created for the server, now we will create one client and it's can use for another client.
Create TCP/IP Client (CLient.vb)
After the server has done, we will create new project in our visual studio and rename it with "TCPClient", and at the Form1.vb just design it look like this images :At the Form1.vb just write all source code below :
Source Code TCP/IP Client
Imports System.Net
Imports System.IO
Imports System.Net.Sockets
Public Class Form1
Dim client As TcpClient
Dim sWriter As StreamWriter
Dim NIckFrefix As Integer = New Random().Next(1111, 9999)
Sub xLoad() Handles Me.Load
Me.Text &= " " & NIckFrefix
End Sub
Delegate Sub _xUpdate(ByVal str As String)
Sub xUpdate(ByVal str As String)
If InvokeRequired Then
Invoke(New _xUpdate(AddressOf xUpdate), str)
Else
TextBox3.AppendText(str & vbNewLine)
End If
End Sub
Sub read(ByVal ar As IAsyncResult)
Try
xUpdate(New StreamReader(client.GetStream).ReadLine)
client.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf read, Nothing)
Catch ex As Exception
xUpdate("You have disconnecting from server")
Exit Sub
End Try
End Sub
Private Sub send(ByVal str As String)
Try
sWriter = New StreamWriter(client.GetStream)
sWriter.WriteLine(str)
sWriter.Flush()
Catch ex As Exception
xUpdate("You're not server")
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Button1.Text = "Connect" Then
Try
client = New TcpClient(TextBox1.Text, CInt(TextBox2.Text))
client.GetStream.BeginRead(New Byte() {0}, 0, 0, New AsyncCallback(AddressOf read), Nothing)
Button1.Text = "Disconnect"
Catch ex As Exception
xUpdate("Can't connect to the server!")
End Try
Else
client.Client.Close()
client = Nothing
Button1.Text = "Connect"
End If
End Sub
Private Sub TextBox4_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox4.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
send(NIckFrefix & " says : " & TextBox4.Text)
TextBox4.Clear()
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
send(NIckFrefix & " says : " & TextBox4.Text)
TextBox4.Clear()
End Sub
End Class
Now, to debugging our simple Multi Client Server Chat Application TCP/IP Client/Server MultiThreaded program, first run the server, after success then run the client, you can run the client.exe from debug folder, and you can open the client exe for many form at he same time.
On the client form, just write at the Server label with : 127.0.0.1 (your server IP) and Port Number : 3818 (i'm using this port)
Thank you for the sample.
RĆ©pondreSupprimerWhat if i want the server to reply to only one client by msg.. not to all connected c?lients
You can help me with the addition DateTime.Hour!
RĆ©pondreSupprimerWhen writing a chat message, these issues also appear DateTime.Hour !
Please cand you help me!
RĆ©pondreSupprimerHow can disconnect the server for block all calls from client?
RĆ©pondreSupprimer