Socket Programming Part 2?

Do you need something made? then ask in here.
Forum rules
Please LOCK your topics once you have found the solution to your question so we know you no longer require help with your query.
6 posts Page 1 of 1
Contributors
User avatar
Frozen
VIP - Donator
VIP - Donator
Posts: 46
Joined: Thu Jul 21, 2011 8:34 pm

Socket Programming Part 2?
Frozen
Well i understand a bit of this "socket" programming but how can i make a socket program which allows the user to login with a username and password to chat?
User avatar
MrAksel
C# Coder
C# Coder
Posts: 1758
Joined: Fri Mar 26, 2010 12:27 pm

Re: Socket Programming Part 2?
MrAksel
Well then you need both a server and a client. I cant understand why everyone is making chat programs now. I was hoping i could be alone :P
You need to have a way to register to the server. The server then checks if the username is registered and the password matches when you send the data. You would want to encrypt the data so thee password is not stolen.
LMAOSHMSFOAIDMT
Laughing my a** of so hard my sombrero fell off and I dropped my taco lmao;


Over 30 projects with source code!
Please give reputation to helpful members!

Image
Image
User avatar
Frozen
VIP - Donator
VIP - Donator
Posts: 46
Joined: Thu Jul 21, 2011 8:34 pm

Re: Socket Programming Part 2?
Frozen
MrAksel wrote:
Well then you need both a server and a client. I cant understand why everyone is making chat programs now. I was hoping i could be alone :P
You need to have a way to register to the server. The server then checks if the username is registered and the password matches when you send the data. You would want to encrypt the data so thee password is not stolen.
Well really it wasnt for a chat program i wanted to make a little online game where you can chat and play.
User avatar
mandai
Coding God
Coding God
Posts: 2585
Joined: Mon Apr 26, 2010 6:51 pm

Re: Socket Programming Part 2?
mandai
Is the chat supposed to be between other clients or just the server? (in terms of destination, not transport)
User avatar
Frozen
VIP - Donator
VIP - Donator
Posts: 46
Joined: Thu Jul 21, 2011 8:34 pm

Re: Socket Programming Part 2?
Frozen
mandai wrote:
Is the chat supposed to be between other clients or just the server? (in terms of destination, not transport)
Other clients(people) so the server hosts this "game" you log in and then you have wherever the spawn is and then you can type to other clients(people) such as you talk and then theres a chatbox where you can see the chat.
User avatar
mandai
Coding God
Coding God
Posts: 2585
Joined: Mon Apr 26, 2010 6:51 pm

Re: Socket Programming Part 2?
mandai
For the game/logon side of things I'd say you need to give more of a protocol draft.

However, I can certainly give examples of TCP client/server chat systems.
You can use this code for the chat server:
Code: Select all
    Delegate Sub del_log(ByVal line As String)

    Sub serverLog(ByVal line As String)
        listServer.Items.Add("[server] " & line)
    End Sub

    Dim clients As List(Of Socket) = New List(Of Socket)
    Dim dataBuffers As List(Of Byte()) = New List(Of Byte())
    Dim lines As List(Of String) = New List(Of String)

    Sub client_BeginReceive(ByVal ar As IAsyncResult)

        Dim client As Socket = ar.AsyncState
        Dim nr As Integer
        Try
            nr = client.EndReceive(ar) 'number of bytes received'
        Catch ex As Exception
            nr = 0
        End Try

        Dim cindex As Integer = clients.IndexOf(client) 'client index'
start:
        If nr = 0 Then

            listServer.Invoke(New del_log(AddressOf serverLog), "Client " & client.RemoteEndPoint.ToString() & " disconnected")

            clients(cindex) = Nothing
            lines(cindex) = Nothing
            dataBuffers(cindex) = Nothing
            client.Close()
        Else
            Dim dec As String = Encoding.ASCII.GetString(dataBuffers(cindex), 0, nr) 'decode text from the number of received bytes'
            For i As Integer = 0 To dec.Length - 1
                lines(cindex) += dec(i)

                If lines(cindex).EndsWith(vbCrLf) Then
                    Dim lineBytes As Byte() = Encoding.ASCII.GetBytes(client.RemoteEndPoint.ToString() & ": " & lines(cindex))
                    For i2 As Integer = 0 To clients.Count - 1
                        If Not clients(i2) Is Nothing Then
                            Try
                                clients(i2).Send(lineBytes)
                            Catch ex As Exception

                                listServer.Invoke(New del_log(AddressOf serverLog), "Error sending client " & cindex & "'s chat to client " & i2)
                            End Try
                        End If
                    Next
                    lines(cindex) = "" 'clear chat buffer of this client as the chat has just been sent'

                End If
            Next

            Try
                client.BeginReceive(dataBuffers(cindex), 0, dataBuffers(cindex).Length, SocketFlags.None, New AsyncCallback(AddressOf client_BeginReceive), client) 'wait for more incoming data'
            Catch ex As Exception
                nr = 0
                GoTo start
            End Try
        End If
    End Sub

    Sub listener_BeginAccept(ByVal ar As IAsyncResult)
        Dim listener As Socket = ar.AsyncState

        Dim client As Socket = listener.EndAccept(ar)

        listServer.Invoke(New del_log(AddressOf serverLog), "Connection accepted from " & client.RemoteEndPoint.ToString())

        clients.Add(client)
        Dim cindex As Integer = clients.IndexOf(client)
        lines.Add("") 'used to store chat before newline sequence <CR><LF> is received'
        dataBuffers.Add(New Byte(9000) {})

        Try
            client.BeginReceive(dataBuffers(cindex), 0, dataBuffers(cindex).Length, SocketFlags.None, New AsyncCallback(AddressOf client_BeginReceive), client) 'wait for incoming data'
        Catch ex As Exception
            listServer.Invoke(New del_log(AddressOf serverLog), "Unable to receive from client")
            clients(cindex) = Nothing
            lines(cindex) = Nothing
            dataBuffers(cindex) = Nothing
            client.Close()
        End Try

        listener.BeginAccept(New AsyncCallback(AddressOf listener_BeginAccept), listener) 'continue accepting new connections'

    End Sub

    Private Sub btnListen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListen.Click

        Dim listener As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

        serverLog("Listening on port 23")
        Dim ep As EndPoint = New IPEndPoint(IPAddress.Any, 23) 'listen on all interfaces, port 23'
        listener.Bind(ep)
        listener.Listen(5)

        listener.BeginAccept(New AsyncCallback(AddressOf listener_BeginAccept), listener)

    End Sub
This code can be used to connect, receive, and send messages to the above server:
Code: Select all
    Delegate Sub del_log(ByVal line As String)

    Sub clientLog(ByVal line As String)
        listClient.Items.Add("[client] " & line)
    End Sub

    Dim cbuffer(9000) As Byte
    Dim line As String = ""

    Sub connectedClient_BeginReceive(ByVal ar As IAsyncResult)

        Dim client As Socket = ar.AsyncState
        Dim nr As Integer
        Try
            nr = client.EndReceive(ar) 'number of bytes received'
        Catch ex As Exception
            nr = 0
        End Try

start:
        If nr = 0 Then
            listClient.Invoke(New del_log(AddressOf clientLog), "Disconnected by remote host")
            client.Close()
        Else
            Dim dec As String = Encoding.ASCII.GetString(cbuffer, 0, nr) 'decode text from the number of received bytes'
            For i As Integer = 0 To dec.Length - 1
                line += dec(i)

                If line.EndsWith(vbCrLf) Then
                    listClient.Invoke(New del_log(AddressOf clientLog), line)
                    line = "" 'clear current received chat buffer'
                End If
            Next

            Try
                client.BeginReceive(cbuffer, 0, cbuffer.Length, SocketFlags.None, New AsyncCallback(AddressOf connectedClient_BeginReceive), client) 'wait for more incoming data'
            Catch ex As Exception
                nr = 0
                GoTo start
            End Try
        End If
    End Sub

    Dim connectedClient As Socket

    Sub client_BeginConnect(ByVal ar As IAsyncResult)

        connectedClient = ar.AsyncState
        Try
            connectedClient.EndConnect(ar)
        Catch ex As Exception
            listClient.Invoke(New del_log(AddressOf clientLog), "Unable to connect")
            Return
        End Try

        Try
            connectedClient.BeginReceive(cbuffer, 0, cbuffer.Length, SocketFlags.None, New AsyncCallback(AddressOf connectedClient_BeginReceive), connectedClient) 'wait for incoming data'
        Catch ex As Exception
            listClient.Invoke(New del_log(AddressOf clientLog), "Unable to receive")
        End Try

    End Sub

    Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click

        Dim client As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

        client.BeginConnect("localhost", 23, New AsyncCallback(AddressOf client_BeginConnect), client)
        'connect to localhost:23'

    End Sub

    Private Sub btnChat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChat.Click
        connectedClient.Send(Encoding.ASCII.GetBytes(txtChat.Text & vbCrLf))
    End Sub
Note: You can also use a Telnet client to join this server.

Feel free to ask any questions.

Edit:
Who thinks it would be a good idea to move this thread out of the VIP section? I have had other people say they can't view it.
6 posts Page 1 of 1
Return to “Tutorial Requests”