Link to home
Start Free TrialLog in
Avatar of addicktz
addicktz

asked on

Simple Question on calling a "as New ..."

ok, I have

Public WithEvents irclient as New SocketsClient

I use this like so....

irclient.connect(address,port)

ok, It allows me to connect than more than one server as it is, and all the data gets parsed correctly on dataarrival, I use this to send to the server....

irClient.SendData(irClient.StringToBytes(txtsend.Text & ControlChars.NewLine))

ok, so my question is, how do i send to a specific server? should I be creating an instance of irclient each time I want a new server? and if so, would I do that with an array? and if an array, how would I do the OnDataArrival which is ......

Private Sub onDataArrival(ByVal Data() As Byte, ByVal totBytes As Integer) Handles irClient.onDataArrival

??
Avatar of tdyck12345
tdyck12345

Yes I think you should use an array to keep track of your objects. When you create the object you can add a handler to it like this:

Dim objIRClient as New SocketsClient
Addhandler objIRClient.onDataArrival, Addressof onDataArrival

I hope that helps,

Troy
Avatar of addicktz

ASKER

ok, where does the array come into play there? or does adding that handler make that instance of objirclient only deal with that instance of data-arrival?
You will need to add the object to the array after creating it so that you still have a reference to the object after you leave the function that creates the object. It could look something like this:

Private m_arrClients as  sClient()

Private Structure sClient
   Dim irClient as SocketClient
   Dim Address as String
   Dim Port as Integer
End Structure

Private Sub onDataArrival(ByVal Data() As Byte, ByVal totBytes As Integer)
  ' handle data arrival
end Sub

Private Sub CreateServer(byref address as string, byref port as integer)
   Dim client as sClient
   sClient.irClient = New SocketsClient
   Addhandler sClient.irClient.onDataArrival, Addressof onDataArrival

   Dim ArrayIndex as integer = 0
   if not m_arrClients is nothing then
      ArrayIndex = m_arrClients.GetLength(0)-1
   end if
   Redim Preserve m_arrClients(ArrayIndex)
   m_arrClients(ArrayIndex) = sClient
end sub

You then have references to the clients and you can send data, connect, etc.

Troy
can you think of a way of where I would know what server the data is coming from, ie, what client just recieved the data?
What kind of information is returned in the onDataArrival parameters? What is content of the Data variable?

Troy
Is the SocketClient class something that you wrote? If so, you could add another parameter in the onDataArrival function that lets you know which server the data is coming from.

Troy
ok, heres my code

Structure server
    Dim address As String
    Dim port As String
    Dim channels As String
    Dim client As SocketsClient
End Structure
Public Class frmMain
    Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents txtConsole As System.Windows.Forms.TextBox
    Friend WithEvents lstServers As System.Windows.Forms.ListBox
    Friend WithEvents lstBots As System.Windows.Forms.ListBox
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents Label3 As System.Windows.Forms.Label
    Friend WithEvents Label4 As System.Windows.Forms.Label
    Friend WithEvents Label5 As System.Windows.Forms.Label
    Friend WithEvents Label6 As System.Windows.Forms.Label
    Friend WithEvents Label7 As System.Windows.Forms.Label
    Friend WithEvents Label8 As System.Windows.Forms.Label
    Friend WithEvents Label9 As System.Windows.Forms.Label
    Friend WithEvents Label10 As System.Windows.Forms.Label
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.txtConsole = New System.Windows.Forms.TextBox
        Me.lstServers = New System.Windows.Forms.ListBox
        Me.lstBots = New System.Windows.Forms.ListBox
        Me.Label1 = New System.Windows.Forms.Label
        Me.Label2 = New System.Windows.Forms.Label
        Me.Label3 = New System.Windows.Forms.Label
        Me.Label4 = New System.Windows.Forms.Label
        Me.Label5 = New System.Windows.Forms.Label
        Me.Label6 = New System.Windows.Forms.Label
        Me.Label7 = New System.Windows.Forms.Label
        Me.Label8 = New System.Windows.Forms.Label
        Me.Label9 = New System.Windows.Forms.Label
        Me.Label10 = New System.Windows.Forms.Label
        Me.SuspendLayout()
        '
        'txtConsole
        '
        Me.txtConsole.Location = New System.Drawing.Point(8, 24)
        Me.txtConsole.Multiline = True
        Me.txtConsole.Name = "txtConsole"
        Me.txtConsole.ScrollBars = System.Windows.Forms.ScrollBars.Both
        Me.txtConsole.Size = New System.Drawing.Size(768, 144)
        Me.txtConsole.TabIndex = 0
        Me.txtConsole.Text = ""
        '
        'lstServers
        '
        Me.lstServers.Location = New System.Drawing.Point(8, 176)
        Me.lstServers.Name = "lstServers"
        Me.lstServers.Size = New System.Drawing.Size(168, 173)
        Me.lstServers.TabIndex = 1
        '
        'lstBots
        '
        Me.lstBots.Location = New System.Drawing.Point(192, 176)
        Me.lstBots.Name = "lstBots"
        Me.lstBots.Size = New System.Drawing.Size(168, 173)
        Me.lstBots.TabIndex = 2
        '
        'Label1
        '
        Me.Label1.Font = New System.Drawing.Font("Times New Roman", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label1.Location = New System.Drawing.Point(368, 184)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(160, 16)
        Me.Label1.TabIndex = 3
        Me.Label1.Text = " "
        Me.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'Label2
        '
        Me.Label2.Font = New System.Drawing.Font("Times New Roman", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label2.Location = New System.Drawing.Point(368, 216)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(160, 16)
        Me.Label2.TabIndex = 4
        Me.Label2.Text = " "
        Me.Label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'Label3
        '
        Me.Label3.Font = New System.Drawing.Font("Times New Roman", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label3.Location = New System.Drawing.Point(368, 248)
        Me.Label3.Name = "Label3"
        Me.Label3.Size = New System.Drawing.Size(160, 16)
        Me.Label3.TabIndex = 5
        Me.Label3.Text = " "
        Me.Label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'Label4
        '
        Me.Label4.Font = New System.Drawing.Font("Times New Roman", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label4.Location = New System.Drawing.Point(368, 280)
        Me.Label4.Name = "Label4"
        Me.Label4.Size = New System.Drawing.Size(160, 16)
        Me.Label4.TabIndex = 6
        Me.Label4.Text = " "
        Me.Label4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'Label5
        '
        Me.Label5.Font = New System.Drawing.Font("Times New Roman", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label5.Location = New System.Drawing.Point(368, 312)
        Me.Label5.Name = "Label5"
        Me.Label5.Size = New System.Drawing.Size(160, 16)
        Me.Label5.TabIndex = 7
        Me.Label5.Text = " "
        Me.Label5.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'Label6
        '
        Me.Label6.Font = New System.Drawing.Font("Times New Roman", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label6.Location = New System.Drawing.Point(544, 312)
        Me.Label6.Name = "Label6"
        Me.Label6.Size = New System.Drawing.Size(160, 16)
        Me.Label6.TabIndex = 12
        Me.Label6.Text = " "
        Me.Label6.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'Label7
        '
        Me.Label7.Font = New System.Drawing.Font("Times New Roman", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label7.Location = New System.Drawing.Point(544, 280)
        Me.Label7.Name = "Label7"
        Me.Label7.Size = New System.Drawing.Size(160, 16)
        Me.Label7.TabIndex = 11
        Me.Label7.Text = " "
        Me.Label7.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'Label8
        '
        Me.Label8.Font = New System.Drawing.Font("Times New Roman", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label8.Location = New System.Drawing.Point(544, 248)
        Me.Label8.Name = "Label8"
        Me.Label8.Size = New System.Drawing.Size(160, 16)
        Me.Label8.TabIndex = 10
        Me.Label8.Text = " "
        Me.Label8.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'Label9
        '
        Me.Label9.Font = New System.Drawing.Font("Times New Roman", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label9.Location = New System.Drawing.Point(544, 216)
        Me.Label9.Name = "Label9"
        Me.Label9.Size = New System.Drawing.Size(160, 16)
        Me.Label9.TabIndex = 9
        Me.Label9.Text = " "
        Me.Label9.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'Label10
        '
        Me.Label10.Font = New System.Drawing.Font("Times New Roman", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label10.Location = New System.Drawing.Point(544, 184)
        Me.Label10.Name = "Label10"
        Me.Label10.Size = New System.Drawing.Size(160, 16)
        Me.Label10.TabIndex = 8
        Me.Label10.Text = " "
        Me.Label10.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'frmMain
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(784, 365)
        Me.Controls.Add(Me.Label6)
        Me.Controls.Add(Me.Label7)
        Me.Controls.Add(Me.Label8)
        Me.Controls.Add(Me.Label9)
        Me.Controls.Add(Me.Label10)
        Me.Controls.Add(Me.Label5)
        Me.Controls.Add(Me.Label4)
        Me.Controls.Add(Me.Label3)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.lstBots)
        Me.Controls.Add(Me.lstServers)
        Me.Controls.Add(Me.txtConsole)
        Me.Name = "frmMain"
        Me.Text = "XDCC MONITOR"
        Me.ResumeLayout(False)

    End Sub

#End Region
    Dim mConn As OleDb.OleDbConnection
    Dim mDataAdapter As New OleDb.OleDbDataAdapter
    Dim mCommandBuilder As OleDb.OleDbCommandBuilder
    Dim mDataSet As New System.Data.DataSet
    Private mServer As server()
    Private servers() As server
    Private WithEvents dumbclient As New SocketsClient

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Const pPROVIDER As String = "Provider=Microsoft.Jet.OLEDB.4.0;"
        Dim pDataSource As String = "Data Source=" & Application.StartupPath & "\servers.mdb"
        mConn = New OleDb.OleDbConnection(pPROVIDER & pDataSource)
        mDataAdapter.SelectCommand = New OleDb.OleDbCommand("SELECT * FROM tblServers", mConn)
        mCommandBuilder = New OleDb.OleDbCommandBuilder(mDataAdapter)
        mDataSet.Clear()
        mDataAdapter.Fill(mDataSet)
        If mDataSet.Tables(0).Rows.Count > 0 Then
            ReDim Preserve servers(mDataSet.Tables(0).Rows.Count - 1)
            Dim xx As Integer
            Dim adkRow As DataRow
            For xx = 0 To mDataSet.Tables(0).Rows.Count - 1
                adkRow = mDataSet.Tables(0).Rows(xx)
                With servers(xx)
                    .address = adkRow!address
                    .port = adkRow!port
                    .channels = adkRow!channels
                End With
                lstServers.Items.Add(adkRow!address)
                dumbclient.Connect(adkRow!address, adkRow!port)
                servers(xx).client = dumbclient
                AddHandler servers(xx).client.onDataArrival, AddressOf onDataArrival
            Next
        End If
    End Sub
    Private Sub onDataArrival(ByVal Data() As Byte, ByVal totBytes As Integer) Handles dumbclient.onDataArrival
        Dim dt As String = dumbclient.BytestoString(Data)
        'ondata(dt)
        txtConsole.AppendText(dt & vbCrLf)
    End Sub
    Public Function nickname() As String
        nickname = "addicktz"
    End Function
    Public Sub oncon() Handles dumbclient.onConnect
        Dim bit() As Byte
        dumbclient.SendData(dumbclient.StringToBytes("NICK " & nickname() & ControlChars.NewLine))
        dumbclient.SendData(dumbclient.StringToBytes("USER " & nickname() & " localhost 0.0.0.0 :" & nickname() & ControlChars.NewLine))
    End Sub
End Class

it sorta works, for some reason its connecting three times to the same server, but i believe that to be a loop problem if anyone catches it, my real question is, using this, how would i identify the client sending the data ? if you could use something like

txtConsole.AppendText(client-array-number & "::" & dt) would be nice =] thank you
this will raise question to worth of 1000 points
500 going to tdyck12345
and the rest going to who can help me with this, thank you
Where can I find the SocketsClient class?

Troy
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Module Module1


    Public Class StateObject
        Public workSocket As Socket = Nothing
        Public BufferSize As Integer = 32767
        Public buffer(32767) As Byte
        Public sb As New StringBuilder
    End Class

    Public Class SocketsClient
        Public Event onConnect()
        Public Event onError(ByVal Description As String, ByVal ln As String)
        Public Event onDataArrival(ByVal Data As Byte(), ByVal TotalBytes As Integer)
        Public Event onDisconnect()
        Public Event onSendComplete(ByVal DataSize As Integer)

        Private Shared response As [String] = [String].Empty
        Private Shared port As Integer = 44
        Private Shared ipHostInfo As IPHostEntry = Dns.Resolve("localhost")
        Private Shared ipAddress As IPAddress = ipHostInfo.AddressList(0)
        Private Shared client As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

        Public Sub Connect(ByVal RemoteHostName As String, ByVal RemotePort As Integer)
            Try
                client = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                port = RemotePort
                ipHostInfo = Dns.Resolve(RemoteHostName)
                ipAddress = ipHostInfo.AddressList(0)
                Dim remoteEP As New IPEndPoint(ipAddress, port)
                client.BeginConnect(remoteEP, AddressOf sockConnected, client)
            Catch
                '   RaiseEvent onError(Err.Description)
                Exit Sub
            End Try
        End Sub

        Public Sub SendData(ByVal Data() As Byte)
            Try
                Dim byteData As Byte() = Data
                client.BeginSend(byteData, 0, byteData.Length, 0, AddressOf sockSendEnd, client)
            Catch
                '  RaiseEvent onError(Err.Description)
                Exit Sub
            End Try
        End Sub

        Public Sub Disconnect()
            Try
                client.Shutdown(SocketShutdown.Both)
            Catch
            End Try
            client.Close()
        End Sub

        Public Function StringToBytes(ByVal Data As String) As Byte()
            StringToBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(Data)
        End Function

        Public Function BytestoString(ByVal Data As Byte()) As String
            BytestoString = System.Text.ASCIIEncoding.ASCII.GetString(Data)
        End Function

        Private Sub sockConnected(ByVal ar As IAsyncResult)
            Try
                '  If client.Connected = False Then RaiseEvent onError("Connection refused.") : Exit Sub
                Dim state As New StateObject
                state.workSocket = client
                client.BeginReceive(state.buffer, 0, state.BufferSize, 0, AddressOf sockDataArrival, state)
                RaiseEvent onConnect()
            Catch
                ' RaiseEvent onError(Err.Description)
                Exit Sub
            End Try
        End Sub

        Private Sub sockDataArrival(ByVal ar As IAsyncResult)
            Dim state As StateObject = CType(ar.AsyncState, StateObject)
            Dim client As Socket = state.workSocket
            Dim bytesRead As Integer

            Try
                bytesRead = client.EndReceive(ar)
            Catch
                Exit Sub
            End Try

            Try
                Dim Data() As Byte = state.buffer
                If bytesRead = 0 Then
                    client.Shutdown(SocketShutdown.Both)
                    client.Close()
                    RaiseEvent onDisconnect()
                    Exit Sub
                End If
                ReDim state.buffer(32767)

                client.BeginReceive(state.buffer, 0, state.BufferSize, 0, AddressOf sockDataArrival, state)
                RaiseEvent onDataArrival(Data, bytesRead)
            Catch
                RaiseEvent onError(Err.Description, Err.Erl)
                Exit Sub
            End Try
        End Sub

        Private Sub sockSendEnd(ByVal ar As IAsyncResult)
            Try
                Dim client As Socket = CType(ar.AsyncState, Socket)
                Dim bytesSent As Integer = client.EndSend(ar)
                RaiseEvent onSendComplete(bytesSent)
            Catch
                '  RaiseEvent onError(Err.Description)
                Exit Sub
            End Try
        End Sub

        Public Function Connected() As Boolean
            Try
                Return client.Connected
            Catch
                'RaiseEvent onError(Err.Description)
                Exit Function
            End Try
        End Function
        Public Function DecodeLongIPAddr(ByVal LongIPAddr As String) As String
            Dim HiWord!
            Dim LoWord!
            Dim Nibble_1, Nibble_2, Nibble_3, Nibble_4 As Integer
            Dim IPAddr As String
            HiWord! = Int(LongIPAddr / 65536)
            LoWord! = LongIPAddr - HiWord! * 65536
            Nibble_1 = Int(HiWord! / 256)
            Nibble_2 = HiWord! - Nibble_1 * 256
            Nibble_3 = Int(LoWord! / 256)
            Nibble_4 = LoWord! - Nibble_3 * 256
            IPAddr = Trim(Str(Nibble_1)) & "."
            IPAddr = IPAddr & Trim(Str(Nibble_2)) & "."
            IPAddr = IPAddr & Trim(Str(Nibble_3)) & "."
            IPAddr = IPAddr & Trim(Str(Nibble_4))
            DecodeLongIPAddr = IPAddr
        End Function

        Public Function EncodeIPAddr(ByVal IPAddr As String) As String
            Dim EIP, DStop, ThisByte As String
            Dim DStart, HiWord, LoWord As Integer
            Dim LongIP As String
            DStart = 1
            EIP = ""
            Do
                DStop = InStr(DStart, IPAddr & ".", ".")
                ThisByte = Hex(Val(Mid$(IPAddr & ".", DStart, DStop - DStart)))
                EIP = EIP & IIf(Len(ThisByte) = 1, "0" & ThisByte, ThisByte)
                DStart = DStop + 1
            Loop Until DStart >= Len(IPAddr & ".")
            HiWord = Val("&H" & Mid(EIP, 1, 2)) * 256.0! + Val("&H" & Mid(EIP, 3, 2))
            LoWord = Val("&H" & Mid(EIP, 5, 2)) * 256.0! + Val("&H" & Mid(EIP, 7, 2))
            LongIP = Str(HiWord * 65536 + LoWord)
            EncodeIPAddr = Trim$(LongIP)
        End Function


    End Class


End Module
???
SocketsClient Changes

Add the following variable and property:

Private m_ID as integer
ReadOnly Property ID() As Integer
     Get
         Return m_ID
     End Get
End Property

Change the onDataArrival event from:

Public Event onDataArrival(ByVal Data As Byte(), ByVal TotalBytes As Integer)

to

Public Event onDataArrival(ByVal ID as Integer, ByVal Data As Byte(), ByVal TotalBytes As Integer)

Then raise the onDataArrival event like so:

RaiseEvent onDataArrival(m_ID, Data, bytesRead)

Change the connect function from:

Public Sub Connect(ByVal RemoteHostName As String, ByVal RemotePort As Integer)
       try
             ...
       catch
       end try
End Sub

to

Public Sub Connect(ByVal ID As Integer, ByVal RemoteHostName As String, ByVal RemotePort As Integer)
       m_ID = ID
       try
             ...
       catch
       end try
End Sub


Make the following changes in frmMain

Change onDataArrival like so:

    Private Sub onDataArrival(ByVal ID As Integer, ByVal Data() As Byte, ByVal totBytes As Integer) Handles dumbclient.onDataArrival
        Dim dt As String = dumbclient.BytestoString(Data)

        If Not servers Is Nothing Then
            Dim clientarraynumber As Integer
            For clientarraynumber = 0 To servers.GetLength(0) - 1
                If servers(clientarraynumber).client.ID = ID Then
                    txtConsole.AppendText(clientarraynumber & "::" & dt & vbCrLf)
                    Exit For
                End If
            Next
        End If
    End Sub

And finally, change

dumbclient.Connect(adkRow!address, adkRow!port)

to

dumbclient.Connect(xx, adkRow!address, adkRow!port)

As far as the problem where you are connecting multiple times, I believe it is the following line of code:

servers(xx).client = dumbclient

At this point you are setting all the clients to the same object. I think you should create a new object at this point.

I hope this helps,

Troy


ASKER CERTIFIED SOLUTION
Avatar of tdyck12345
tdyck12345

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial