Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Programming a tcp chat with client/serversockets

$
0
0
Hello there people of dreamincode,

I'm Currently trying to program a TCP chat in VB.net with a clientsocket and a serversocket. I'm pretty noob at it and any assistance would be greatly appreciated. Trying to get alot of bugs out. I copied source code from a website and changed alot.
My code for clientsocket:
Imports System.Net.Sockets
Imports System.Text

Public Class Form1
    Dim clientSocket As New System.Net.Sockets.TcpClient()
    Dim serverStream As NetworkStream
    Dim readData As String
    Dim user As String


    Private Sub BtnConnect_Click(sender As Object, e As System.EventArgs) Handles BtnConnect.Click
        'LocalHostName
        Dim StrlocalHostName As String
        StrlocalHostName = System.Net.Dns.GetHostName()
        'Ip Address
        Dim StrIpAddress As String
        StrIpAddress = System.Net.Dns.GetHostEntry(StrlocalHostName).AddressList(0).ToString()

        If TxtChatnaam.Text = String.Empty Then
            MessageBox.Show("Please fill in your Chatname.", "No name found", MessageBoxButtons.OK, MessageBoxIcon.Information)

        ElseIf clientSocket.Connected = True Then
            MessageBox.Show("Already Connected to the chat!", "Already Connected", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Else
            user = TxtChatnaam.Text
            readData = "Connecting to Dre's Chat Server ..."
            msg()
            If IsPortAvailable("127.0.0.1", 8888) = True Then

                TxtUsers.Text &= TxtChatnaam.Text & Environment.NewLine

                serverStream = clientSocket.GetStream()

                Dim outStream As Byte() = System.Text.Encoding.ASCII.GetBytes(TxtChatnaam.Text + "$")
                serverStream.Write(outStream, 0, outStream.Length)
                serverStream.Flush()

                Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf getMessage)
                ctThread.Start()
            Else
                MessageBox.Show("Server offline.", "Server offline", MessageBoxButtons.OK, MessageBoxIcon.Information)
                TxtBerichten.Clear()
                TxtBerichten.Text = " >> Could not connect to the Server" & Environment.NewLine & " >> Please come back later."

            End If


        End If


    End Sub

    Private Sub BtnSendMessage_Click(sender As Object, e As System.EventArgs) Handles BtnSendMessage.Click
        If TxtSendMessage.Text = String.Empty Then
        Else
            Dim outStream As Byte() = System.Text.Encoding.ASCII.GetBytes(TxtSendMessage.Text + "$")
            serverStream.Write(outStream, 0, outStream.Length)
            serverStream.Flush()
            TxtSendMessage.Text = String.Empty
        End If
        
    End Sub

    Private Sub msg()
        If Me.InvokeRequired Then
            Me.Invoke(New MethodInvoker(AddressOf msg))
        Else
            TxtBerichten.Text = TxtBerichten.Text + Environment.NewLine + " >> " + readData
        End If
    End Sub

    Private Sub getMessage()

        Dim infiniteCounter As Integer

        Try
            For infiniteCounter = 1 To 2
                infiniteCounter = 1
                serverStream = clientSocket.GetStream()
                Dim buffSize As Integer
                Dim inStream(10024) As Byte
                buffSize = clientSocket.ReceiveBufferSize
                serverStream.Read(inStream, 0, buffSize)
                Dim returndata As String = System.Text.Encoding.ASCII.GetString(inStream)
                readData = "" + returndata
                msg()
            Next

        Catch ex As Exception
            MessageBox.Show("You have left the chat", "Disconnected", MessageBoxButtons.OK, MessageBoxIcon.Information)

        End Try






    End Sub

    Private Sub BtnLeave_Click(sender As Object, e As System.EventArgs) Handles BtnLeave.Click
        Dim outStream As Byte() = System.Text.Encoding.ASCII.GetBytes(user & " has left the chatroom" + "$")

        If TxtUsers.Text = String.Empty Then
            TxtUsers.Text = TxtUsers.Text
        Else
            TxtUsers.Clear()

            readData = user & " has left the chatroom."


            serverStream.Write(outStream, 0, outStream.Length)
            serverStream.Flush()
            msg()

            serverStream.Close()
            'Socketverbinding sluiten?
            clientSocket.Close()


        End If

    End Sub


    Private Function IsPortAvailable(Ip As String, Port As Integer) As Boolean
        Try
            clientSocket.Connect(Ip, Port)
            Return True

        Catch ex As Exception
            Return False

        End Try

    End Function
End Class


Serversocket:
Imports System.Net.Sockets
Imports System.Text
Imports System.Net

Module Module1
    Dim clientsList As New Hashtable

    Sub Main()
        Dim serverSocket As New TcpListener(8888)
        Dim clientSocket As New TcpClient
        Dim infiniteCounter As Integer
        Dim counter As Integer

        serverSocket.Start()
        msg("Dre's Chat Server Started ...")
        counter = 0
        infiniteCounter = 0
        For infiniteCounter = 1 To 2
            infiniteCounter = 1
            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 handleClient
            client.startClient(clientSocket, dataFromClient, clientsList)
        Next

        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 handleClient
        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

            If clientSocket.Connected = True Then
                requestCount = 0
                For infiniteCounter = 1 To 2
                    infiniteCounter = 1
                    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("van client - " + clNo + " : " + dataFromClient)
                        rCount = Convert.ToString(requestCount)

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

            
        End Sub

    End Class

End Module


What im trying to find out is.
- I have a textbox called txtUsers, i'm trying to get all names of the connected users in there. How do i do this?
- If i click on leave chat button, i want to close all the sockets, disconnect and stuff and then have a messagebox pop up saying you have been disconnected. if then i enter a new name in the textbox i connect again with another username.


Any help would be greatly appreciated! Thanks folks
Design is in the attachment!

Viewing all articles
Browse latest Browse all 51036

Trending Articles