Chat Server Crashing
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Chat Server Crashing

  1. #1
    Join Date
    Jul 2013
    Location
    .NET 4.0
    Posts
    1

    Chat Server Crashing

    Hello everyone, I am new here.

    I am currently having an issue with a Login server I am trying to make. Its a basic Multithreaded TCP server and it does work, but after some time (couple of hours to about 2 days) the server randomly stops accepting new connections. The server works like this: the main thread listens for incoming connections, after somebody connects it starts a new thread for them, which then connects to the MySQL database and checks if their username/password is correct.

    During some parts of the day this server might receive about 1000 login requests an hour, it was working fine for most part in the past when it was only 50-100 an hour.

    Code:
    Imports MySql.Data.MySqlClient
    Imports System.Net.Sockets
    Imports System.IO
    Imports System.Net
    Imports System
    Imports System.Security
    Imports System.Security.Cryptography
    Imports System.Runtime.InteropServices
    Imports System.Text.RegularExpressions
    Imports System.Text
    
    Module Module1
        Private server As TcpListener
        Private client As New TcpClient
        Private ipendpoint As IPEndPoint = New IPEndPoint(IPAddress.Any, 2081)
        Private list As New List(Of Connection)
        Private onlineuserlist As New List(Of String)
        Public AllConnections As Integer = 0
    
        Private Structure Connection
            Dim stream As NetworkStream
            Dim streamw As StreamWriter
            Dim streamr As StreamReader
            Dim nick As String
        End Structure
    
        Sub Main()
            Try
                Console.WriteLine("Server Started!")
                server = New TcpListener(ipendpoint)
                server.Start()
    
                While True
                    Console.WriteLine("Waiting for a new client!")
                    Try
                        client = server.AcceptTcpClient
                    Catch ex As Exception
                        Console.WriteLine("Exception 101: " & ex.ToString)
                    End Try
                    Console.WriteLine("New Client Attempting to connect!")
                    Try
                        Dim c As New Connection
                        c.stream = client.GetStream
                        c.streamr = New StreamReader(c.stream)
                        c.streamw = New StreamWriter(c.stream)
    
                        c.nick = c.streamr.ReadLine
                        Console.WriteLine(c.nick & " is attempting to log in!")
    
                        list.Add(c)
                        Console.WriteLine("Current Connection Count: " & list.Count.ToString)
    
                        Dim t As New Threading.Thread(AddressOf ListenToConnection)
                        t.Start(c)
                        Console.WriteLine("Connection Thread Started!")
    
                        AllConnections += 1
                        Console.WriteLine("All Connections Count: " & AllConnections)
    
                    Catch ex As Exception
                        Console.WriteLine("Exception 102: " & ex.ToString)
                    End Try
                End While
            Catch ex As Exception
                Console.WriteLine("Exception 103: " & ex.ToString)
            End Try
        End Sub
    
        Private Sub ListenToConnection(ByVal con As Connection)
            Try
                Dim conn As New MySqlConnection
                conn.ConnectionString = "server=127.0.0.1;Port=3306; user id=id; password=pass; database=db"
    
                Do
                    Try
                        Dim tmp As String = con.streamr.ReadLine
                        Console.WriteLine("Thread Online!")
                        Dim sParts() As String
                        sParts = Split(tmp, "/\/\")
    
                        If sParts(0) = "Login" Then
                            Try
                                conn.Open()
    
                                Dim myAdapter As New MySqlDataAdapter
                                Dim sqlquery As String
                                Dim myCommand As New MySqlCommand
                                Dim Mydata As MySqlDataReader
    
                                sqlquery = "Select * From account WHERE Username='" & sParts(1) & "'AND Password='" & sParts(2) & "';"
                                myCommand.Connection = conn
                                myCommand.CommandText = sqlquery
                                myAdapter.SelectCommand = myCommand
                                Mydata = myCommand.ExecuteReader
                                Mydata.Read()
    
                                If Mydata.HasRows = True Then
                                    If Mydata.GetString("Ban") <> "1" Then
    
                                        con.streamw.WriteLine(Encrypt("LoginVerified/\/\" & Mydata.GetString("Username") & "/\/\" & Mydata.GetString("Rank") & "/\/\" & Mydata.GetString("WP") & "/\/\" & Mydata.GetString("Team") & "/\/\" & Mydata.GetString("Rating") & "/\/\" & Mydata.GetString("Gold") & "/\/\" & Mydata.GetString("Win") & "/\/\" & Mydata.GetString("Draw") & "/\/\" & Mydata.GetString("Lost")))
                                        con.streamw.Flush()
    
                                        Dim PlayerTeam As String = Mydata.GetString("Team")
                                        Dim PlayerUsername As String = Mydata.GetString("Username")
    
    
                                        Try
                                            If Mydata.GetString("Friends") <> "" Then
                                                Dim fParts() As String
                                                fParts = Split(Mydata.GetString("Friends"), "+/|")
                                                For Each FriendPlayer As String In fParts
                                                    For Each c As Connection In list
                                                        c.streamw.WriteLine(Encrypt("AddFriend/\/\" & FriendPlayer))
                                                        c.streamw.Flush()
                                                    Next
                                                Next
                                            End If
    
                                            If Mydata.GetString("Team") <> "" Then
                                                conn.Close()
                                                Try
                                                    conn.Open()
                                                Catch
                                                End Try
                                                sqlquery = "SELECT * FROM teams WHERE Name = '" & PlayerTeam & "'"
                                                myCommand.Connection = conn
                                                myCommand.CommandText = sqlquery
                                                myAdapter.SelectCommand = myCommand
                                                Mydata = myCommand.ExecuteReader
                                                Mydata.Read()
                                                If Mydata.HasRows <> 0 Then
                                                    con.streamw.WriteLine(Encrypt("SendTeam/\/\" & PlayerUsername & "/\/\" & Mydata.GetString("Leader")))
                                                    con.streamw.Flush()
                                                    If Mydata.GetString("Members") <> "" Then
                                                        Dim hParts() As String
                                                        hParts = Split(Mydata.GetString("Members"), "+/|")
                                                        For Each TeamPlayer As String In hParts
                                                            con.streamw.WriteLine(Encrypt("AddTeam/\/\" & TeamPlayer))
                                                            con.streamw.Flush()
                                                        Next
                                                    End If
                                                End If
                                            End If
                                            conn.Close()
                                        Catch
                                        End Try
                                        conn.Close()
                                        con.streamw.WriteLine(Encrypt("ConnectToChatServer/\/\" & con.nick))
                                        con.streamw.Flush()
    
                                        Try
                                            conn.Close()
                                            conn.Open()
    
                                            sqlquery = "UPDATE account SET CPUID = '" & sParts(3) & "' WHERE username = '" & sParts(1) & "'"
                                            myCommand.Connection = conn
                                            myCommand.CommandText = sqlquery
                                            myAdapter.SelectCommand = myCommand
                                            Mydata = myCommand.ExecuteReader
    
                                            conn.Close()
                                            conn.Open()
    
                                            sqlquery = "UPDATE account SET IP = '" & sParts(4) & "' WHERE username = '" & sParts(1) & "'"
                                            myCommand.Connection = conn
                                            myCommand.CommandText = sqlquery
                                            myAdapter.SelectCommand = myCommand
                                            Mydata = myCommand.ExecuteReader
    
                                            conn.Close()
                                            conn.Open()
    
                                            sqlquery = "UPDATE account SET ComputerName = '" & sParts(5) & "' WHERE username = '" & sParts(1) & "'"
                                            myCommand.Connection = conn
                                            myCommand.CommandText = sqlquery
                                            myAdapter.SelectCommand = myCommand
                                            Mydata = myCommand.ExecuteReader
    
                                            conn.Dispose()
                                        Catch
                                            conn.Dispose()
                                            list.Remove(con)
                                            Exit Do
                                        End Try
                                        conn.Dispose()
                                        list.Remove(con)
                                        Exit Do
                                    Else
                                        conn.Dispose()
                                        list.Remove(con)
                                        Exit Do
                                    End If
                                Else
                                    Try
                                        con.streamw.WriteLine(Encrypt("WrongPassword/\/\" & sParts(1)))
                                        con.streamw.Flush()
                                        conn.Dispose()
                                        list.Remove(con)
                                        Exit Do
                                    Catch
                                        conn.Dispose()
                                        list.Remove(con)
                                        Exit Do
                                    End Try
                                End If
                                conn.Dispose()
                            Catch
                                conn.Dispose()
                            End Try
                        ElseIf sParts(0) = "Register" Then
                            conn.Open()
                            Dim myAdapter As New MySqlDataAdapter
                            Dim sqlquery = "SELECT * FROM account WHERE username = '" & sParts(1) & "'"
                            Dim myCommand As New MySqlCommand()
                            myCommand.Connection = conn
                            myCommand.CommandText = sqlquery
                            myAdapter.SelectCommand = myCommand
                            Dim myData As MySqlDataReader
                            myData = myCommand.ExecuteReader
                            If myData.HasRows = 0 Then
                                conn.Close()
                                conn.Open()
    
                                Dim registerfinal As New MySqlDataAdapter
                                sqlquery = "INSERT INTO account (Username, Password, Ban, Referral) VALUES ('" & sParts(1) & "','" & sParts(2) & "','" & "0" & "','" & sParts(4) & "')"
                                myCommand.Connection = conn
                                myCommand.CommandText = sqlquery
                                registerfinal.SelectCommand = myCommand
                                myData = myCommand.ExecuteReader
                                Try
                                    con.streamw.WriteLine(Encrypt("RegisterComplete/\/\" & sParts(1)))
                                    con.streamw.Flush()
                                    conn.Dispose()
                                    list.Remove(con)
                                    Exit Do
                                Catch
                                    conn.Dispose()
                                    list.Remove(con)
                                    Exit Do
                                End Try
                            Else
                                Try
                                    con.streamw.WriteLine(Encrypt("RegisterFail/\/\" & sParts(1)))
                                    con.streamw.Flush()
                                    conn.Dispose()
                                    list.Remove(con)
                                    Exit Do
                                Catch
                                    conn.Dispose()
                                    list.Remove(con)
                                    Exit Do
                                End Try
                            End If
                            conn.Dispose()
                        Else
                            conn.Dispose()
                            list.Remove(con)
                            Exit Do
                        End If
                    Catch ex As Exception
                        conn.Dispose()
                        list.Remove(con)
                        Exit Do
                    End Try
                Loop
            Catch ex As Exception
                Console.WriteLine("Exception 104: " & ex.ToString)
            End Try
        End Sub
        Public Function Encrypt(ByVal plainText As String) As String
            Try
                Dim passPhrase As String = "g4gsdafc"
                Dim saltValue As String = "sgaege3r"
                Dim hashAlgorithm As String = "SHA1"
                Dim passwordIterations As Integer = 2
                Dim initVector As String = "@1B2c3D4e5F6g7H8"
                Dim keySize As Integer = 256
                Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
                Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
                Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)
                Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
                Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
                Dim symmetricKey As New RijndaelManaged()
                symmetricKey.Mode = CipherMode.CBC
                Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)
                Dim memoryStream As New MemoryStream()
                Dim cryptoStream As New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
                cryptoStream.FlushFinalBlock()
                Dim cipherTextBytes As Byte() = memoryStream.ToArray()
                memoryStream.Close()
                cryptoStream.Close()
                Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)
                Return cipherText
            Catch
                Return "Error"
            End Try
        End Function
    End Module

  2. #2
    Join Date
    Jan 2006
    Location
    Chicago, IL
    Posts
    14,990

    Re: Chat Server Crashing

    Need more bandwidth on the server end, or a faster server. Look into HOSTING it somewhere. AZURE can handle a lot more than that.
    David

    CodeGuru Article: Bound Controls are Evil-VB6
    2013 Samples: MS CODE Samples

    CodeGuru Reviewer
    2006 Dell CSP
    2006, 2007 & 2008 MVP Visual Basic
    If your question has been answered satisfactorily, and it has been helpful, then, please, Rate this Post!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center