TCPListener

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • iwdu15

    #1

    TCPListener

    hi i have a working code for a tcpclient, but i cant seemt of figure out how
    to use a tcplistener to connect with it. i just want to clck a button and
    listen for a TCP conection and conect to a specific port, but any attempt i
    try fails....any help would b awsome
    --
    -iwdu15
  • Mike

    #2
    Re: TCPListener

    Send your code to see what we can do

    -----Original Message-----
    From: iwdu15 [mailto:iwdu15@d iscussions.micr osoft.com]
    Posted At: Wednesday, September 28, 2005 10:37 PM
    Posted To: microsoft.publi c.dotnet.langua ges.vb
    Conversation: TCPListener
    Subject: TCPListener

    hi i have a working code for a tcpclient, but i cant seemt of figure out
    how
    to use a tcplistener to connect with it. i just want to clck a button
    and
    listen for a TCP conection and conect to a specific port, but any
    attempt i
    try fails....any help would b awsome
    --
    -iwdu15

    Comment

    • iwdu15

      #3
      Re: TCPListener

      ok, heres the code i tried for listening async:

      #Region "Declaratio ns"

      Dim homeip As Net.IPAddress
      Dim ClientSocket As Net.Sockets.Soc ket
      Dim ASCII As New System.Text.ASC IIEncoding

      Dim ListenSocket As Net.Sockets.Soc ket

      #End Region

      #Region "Listen"

      Private Sub btnlisten_Click (ByVal sender As System.Object, ByVal e As
      System.EventArg s) Handles btnlisten.Click

      Call Listen(homeip, Me.txtlistenpor t.Text)

      End Sub

      Private Sub Listen(ByVal IP As IPAddress, ByVal port As Integer)

      Dim ep As New Net.IPEndPoint( IP, port)

      ListenSocket = New Net.Sockets.Soc ket(AddressFami ly.InterNetwork ,
      SocketType.Stre am, ProtocolType.Tc p)

      ListenSocket.Be ginAccept(Addre ssOf ListenCallBack, Nothing)

      End Sub

      Private Sub ListenCallBack( ByVal ar As IAsyncResult)

      Try
      ListenSocket.En dAccept(ar)

      'Begin Receiveing Data
      Dim bytes(4095) As Byte
      ClientSocket.Be ginReceive(byte s, 0, bytes.Length,
      SocketFlags.Non e, AddressOf ListenReceiveCa llBack, bytes)

      Catch ex As Exception
      Me.rtbinfo.Text += vbNewLine & ex.Message & vbNewLine
      End Try

      End Sub

      Private Sub ListenReceiveCa llBack(ByVal ar As IAsyncResult)

      Dim bytes() As Byte = CType(ar.AsyncS tate, Byte())
      Dim numbytes As Int32 = ListenSocket.En dReceive(ar)

      If numbytes = 0 Then

      ListenSocket.Sh utdown(SocketSh utdown.Both)
      ListenSocket.Cl ose()

      Else

      Dim recv As String = ASCII.GetString (bytes, 0, numbytes)

      'Clear the buffer
      Array.Clear(byt es, 0, bytes.Length)

      'Begin Receive Again
      ClientSocket.Be ginReceive(byte s, 0, bytes.Length,
      SocketFlags.Non e, AddressOf ListenReceiveCa llBack, bytes)

      End If

      End Sub

      #End Region

      thanks

      -iwdu15

      Comment

      • Dragon

        #4
        Re: TCPListener

        Hi,

        A few comments about your code.

        1. I don't see whether you assigned something to homeip.
        2. I don't see if you bound ListenSocket to homeip, and put it into
        listening state.
        3. I don't see where you assigned something to ClientSocket before
        receiving data from it.
        4. In ListenReceiveCa llBack routine you call EndReceive from
        ListenSocket, not ClientSocket.

        So,

        1.Assign something to homeip. For example, IPAddress.Any.
        2. Insert ~ ListenSocket.Bi nd(ep) ~ and ~ ListenSocket.Li sten(0) ~ prior
        to call to ListenSocket.Be ginAccept().
        3. Change ~ ListenSocket.En dAccept(ar) ~ to ~ ClientSocket =
        ListenSocket.En dAccept(ar) ~.
        4. Change ~ ListenSocket.En dReceive ~ to ~ ClientSocket.En dReceive ~.

        Hope this helps,
        Roman

        "iwdu15" <iwdu15@discuss ions.microsoft. com> ÓÏÏÂÝÉÌ/ÓÏÏÂÝÉÌÁ × ÎÏ×ÏÓÔÑÈ
        ÓÌÅÄÕÀÝÅÅ: news:B41004B0-537F-4B1A-987F-E739692AA2F3@mi crosoft.com...[color=blue]
        > ok, heres the code i tried for listening async:
        >
        > #Region "Declaratio ns"
        >
        > Dim homeip As Net.IPAddress
        > Dim ClientSocket As Net.Sockets.Soc ket
        > Dim ASCII As New System.Text.ASC IIEncoding
        >
        > Dim ListenSocket As Net.Sockets.Soc ket
        >
        > #End Region
        >
        > #Region "Listen"
        >
        > Private Sub btnlisten_Click (ByVal sender As System.Object, ByVal e[/color]
        As[color=blue]
        > System.EventArg s) Handles btnlisten.Click
        >
        > Call Listen(homeip, Me.txtlistenpor t.Text)
        >
        > End Sub
        >
        > Private Sub Listen(ByVal IP As IPAddress, ByVal port As Integer)
        >
        > Dim ep As New Net.IPEndPoint( IP, port)
        >
        > ListenSocket = New[/color]
        Net.Sockets.Soc ket(AddressFami ly.InterNetwork ,[color=blue]
        > SocketType.Stre am, ProtocolType.Tc p)
        >
        > ListenSocket.Be ginAccept(Addre ssOf ListenCallBack, Nothing)
        >
        > End Sub
        >
        > Private Sub ListenCallBack( ByVal ar As IAsyncResult)
        >
        > Try
        > ListenSocket.En dAccept(ar)
        >
        > 'Begin Receiveing Data
        > Dim bytes(4095) As Byte
        > ClientSocket.Be ginReceive(byte s, 0, bytes.Length,
        > SocketFlags.Non e, AddressOf ListenReceiveCa llBack, bytes)
        >
        > Catch ex As Exception
        > Me.rtbinfo.Text += vbNewLine & ex.Message & vbNewLine
        > End Try
        >
        > End Sub
        >
        > Private Sub ListenReceiveCa llBack(ByVal ar As IAsyncResult)
        >
        > Dim bytes() As Byte = CType(ar.AsyncS tate, Byte())
        > Dim numbytes As Int32 = ListenSocket.En dReceive(ar)
        >
        > If numbytes = 0 Then
        >
        > ListenSocket.Sh utdown(SocketSh utdown.Both)
        > ListenSocket.Cl ose()
        >
        > Else
        >
        > Dim recv As String = ASCII.GetString (bytes, 0, numbytes)
        >
        > 'Clear the buffer
        > Array.Clear(byt es, 0, bytes.Length)
        >
        > 'Begin Receive Again
        > ClientSocket.Be ginReceive(byte s, 0, bytes.Length,
        > SocketFlags.Non e, AddressOf ListenReceiveCa llBack, bytes)
        >
        > End If
        >
        > End Sub
        >
        > #End Region
        >
        > thanks
        >
        > -iwdu15[/color]


        Comment

        • Supra

          #5
          Re: TCPListener


          there is tutorial or use some googlle search

          iwdu15 wrote:
          [color=blue]
          >hi i have a working code for a tcpclient, but i cant seemt of figure out how
          >to use a tcplistener to connect with it. i just want to clck a button and
          >listen for a TCP conection and conect to a specific port, but any attempt i
          >try fails....any help would b awsome
          >
          >[/color]

          Comment

          • iwdu15

            #6
            Re: TCPListener

            well that wasnt all my code, that was just relavant to the listening paert,
            if u want i can show all my code, but homeip is used in the formload event to
            get the IP address from the computer its running on, and clientsocket wis
            used to send the connect request in my other code and the code endrecieve is
            in there, il just list all my code here:

            #Region "Declaratio ns"

            Dim homeip As Net.IPAddress
            Dim ClientSocket As Net.Sockets.Soc ket
            Dim ASCII As New System.Text.ASC IIEncoding

            Dim ListenSocket As Net.Sockets.Soc ket

            #End Region

            #Region "Connect"

            Private Sub Form1_Load(ByVa l sender As System.Object, ByVal e As
            System.EventArg s) Handles MyBase.Load

            homeip =
            Net.Dns.GetHost ByName(Net.Dns. GetHostName).Ad dressList.GetVa lue(0)

            Me.Text = homeip.ToString

            End Sub

            Private Sub btnconnect_Clic k(ByVal sender As System.Object, ByVal e As
            System.EventArg s) Handles btnconnect.Clic k

            Dim addr As Net.IPAddress =
            Net.Dns.Resolve (Me.txtIP.Text) .AddressList(0)

            If Not addr Is Nothing Then
            'Create IP endpoint
            Dim EP As New Net.IPEndPoint( addr, CInt(Me.txtport .Text))

            'create socket
            ClientSocket = New
            Net.Sockets.Soc ket(Net.Sockets .AddressFamily. InterNetwork,
            Net.Sockets.Soc ketType.Stream, Net.Sockets.Pro tocolType.Tcp)

            'Connect
            ClientSocket.Be ginConnect(EP, AddressOf ConnectCallBack , Nothing)

            End If

            End Sub

            Private Sub ConnectCallBack (ByVal ar As IAsyncResult)

            Try
            ClientSocket.En dConnect(ar)

            Dim dlg As New NoParamsDelegat e(AddressOf ConnectedUI)

            Me.Invoke(dlg)

            'Begin Receiveing Data
            Dim bytes(4095) As Byte
            ClientSocket.Be ginReceive(byte s, 0, bytes.Length,
            SocketFlags.Non e, AddressOf ReceiveCallBack , bytes)

            Catch ex As Exception
            Me.rtbinfo.Text += vbNewLine & ex.Message & vbNewLine
            End Try

            End Sub

            Private Delegate Sub NoParamsDelegat e()

            Private Sub ConnectedUI()

            Me.rtbinfo.Text += vbNewLine & "Connected" & vbNewLine

            Me.btnconnect.E nabled = False
            Me.btnsend.Enab led = True
            Me.rtbsend.Focu s()

            End Sub

            Private Sub DisconnectedUI( )

            Me.rtbinfo.Text += vbNewLine & "Disconnect ed" & vbNewLine

            Me.btnconnect.E nabled = True
            Me.btnsend.Enab led = False
            Me.btnconnect.F ocus()

            End Sub

            Private Sub ReceiveCallBack (ByVal ar As IAsyncResult)

            Dim bytes() As Byte = CType(ar.AsyncS tate, Byte())
            Dim numbytes As Int32 = ClientSocket.En dReceive(ar)

            If numbytes = 0 Then
            ClientSocket.Sh utdown(SocketSh utdown.Both)
            ClientSocket.Cl ose()

            Dim dlg As New NoParamsDelegat e(AddressOf DisconnectedUI)

            Me.Invoke(dlg)
            Else
            Dim recv As String = ASCII.GetString (bytes, 0, numbytes)

            'Clear the buffer
            Array.Clear(byt es, 0, bytes.Length)

            'Show in UI
            Dim dlg As New OneStringDelega te(AddressOf DisplayReceived Data)
            Dim args() As Object = {recv}

            Me.Invoke(dlg, args)

            'Begin Receive Again
            ClientSocket.Be ginReceive(byte s, 0, bytes.Length,
            SocketFlags.Non e, AddressOf ReceiveCallBack , bytes)

            End If

            End Sub

            Private Sub DisplayReceived Data(ByVal data As String)

            With Me.rtbsend
            .SelectionStart = .Text.Length
            .SelectedText = data

            End With

            End Sub

            Private Delegate Sub OneStringDelega te(ByVal data As String)

            Private Sub btnsend_Click(B yVal sender As System.Object, ByVal e As
            System.EventArg s) Handles btnsend.Click

            Dim bytes() As Byte = ASCII.GetBytes( Me.txtsend.Text )
            ClientSocket.Se nd(bytes)

            End Sub

            #End Region

            #Region "Listen"

            Private Sub btnlisten_Click (ByVal sender As System.Object, ByVal e As
            System.EventArg s) Handles btnlisten.Click

            Call Listen(homeip, Me.txtlistenpor t.Text)

            End Sub

            Private Sub Listen(ByVal IP As IPAddress, ByVal port As Integer)

            Dim ep As New Net.IPEndPoint( IP, port)

            ListenSocket = New Net.Sockets.Soc ket(AddressFami ly.InterNetwork ,
            SocketType.Stre am, ProtocolType.Tc p)

            ListenSocket.Be ginAccept(Addre ssOf ListenCallBack, Nothing)

            End Sub

            Private Sub ListenCallBack( ByVal ar As IAsyncResult)

            Try
            ListenSocket.En dAccept(ar)

            'Begin Receiveing Data
            Dim bytes(4095) As Byte
            ClientSocket.Be ginReceive(byte s, 0, bytes.Length,
            SocketFlags.Non e, AddressOf ListenReceiveCa llBack, bytes)

            Catch ex As Exception
            Me.rtbinfo.Text += vbNewLine & ex.Message & vbNewLine
            End Try

            End Sub

            Private Sub ListenReceiveCa llBack(ByVal ar As IAsyncResult)

            Dim bytes() As Byte = CType(ar.AsyncS tate, Byte())
            Dim numbytes As Int32 = ListenSocket.En dReceive(ar)

            If numbytes = 0 Then

            ListenSocket.Sh utdown(SocketSh utdown.Both)
            ListenSocket.Cl ose()

            Else

            Dim recv As String = ASCII.GetString (bytes, 0, numbytes)

            'Clear the buffer
            Array.Clear(byt es, 0, bytes.Length)

            'Begin Receive Again
            ClientSocket.Be ginReceive(byte s, 0, bytes.Length,
            SocketFlags.Non e, AddressOf ListenReceiveCa llBack, bytes)

            End If

            End Sub

            #End Region

            Comment

            • Dragon

              #7
              Re: TCPListener


              "iwdu15" <iwdu15@discuss ions.microsoft. com> ÓÏÏÂÝÉÌ/ÓÏÏÂÝÉÌÁ × ÎÏ×ÏÓÔÑÈ
              ÓÌÅÄÕÀÝÅÅ: news:B2EF8CEA-0254-4F26-AC05-A347DE415E34@mi crosoft.com...[color=blue]
              > well that wasnt all my code, that was just relavant to the listening[/color]
              paert,[color=blue]
              > if u want i can show all my code, but homeip is used in the formload[/color]
              event to[color=blue]
              > get the IP address from the computer its running on, and clientsocket[/color]
              wis[color=blue]
              > used to send the connect request in my other code and the code[/color]
              endrecieve is[color=blue]
              > in there, il just list all my code here:[/color]

              Okay, forget point #1 8=].
              But look again at other my suggestions and try to implement them.

              Roman


              Comment

              • iwdu15

                #8
                Re: TCPListener

                ok, i tried binding the ListenSocket to an endpoint, and it gives an object
                reference exception, heres the code, and homeIP and me.txtlistenip. text both
                have values in them:

                Private Sub btnlisten_Click (ByVal sender As System.Object, ByVal e As
                System.EventArg s) Handles btnlisten.Click

                Call Listen(homeip, Me.txtlistenpor t.Text)

                End Sub

                Private Sub Listen(ByVal IP As IPAddress, ByVal port As Integer)

                Dim ep As New Net.IPEndPoint( IP, port)

                ListenSocket.Bi nd(ep)

                ListenSocket.Li sten(50)

                ListenSocket = New Net.Sockets.Soc ket(AddressFami ly.InterNetwork ,
                SocketType.Stre am, ProtocolType.Tc p)

                ListenSocket.Be ginAccept(Addre ssOf ListenCallBack, Nothing)

                End Sub

                Comment

                • Dragon

                  #9
                  Re: TCPListener

                  > Private Sub Listen(ByVal IP As IPAddress, ByVal port As Integer)[color=blue]
                  >
                  > Dim ep As New Net.IPEndPoint( IP, port)
                  >
                  > ListenSocket.Bi nd(ep)
                  >
                  > ListenSocket.Li sten(50)
                  >
                  > ListenSocket = New[/color]
                  Net.Sockets.Soc ket(AddressFami ly.InterNetwork ,[color=blue]
                  > SocketType.Stre am, ProtocolType.Tc p)
                  >
                  > ListenSocket.Be ginAccept(Addre ssOf ListenCallBack, Nothing)
                  >
                  > End Sub[/color]

                  Eh, you should first create a socket *before* calling methods on it,
                  shouldn't you?

                  ListenSocket = New Socket(...)
                  ListenSocket.Bi nd(...)
                  ListenSocket.Li sten(...)
                  ListenSocket.Be ginAccept(...)

                  Roman


                  Comment

                  • iwdu15

                    #10
                    Re: TCPListener

                    whups, n00b error there, thanks for pointing that out, but now i havbe a
                    problem. il show the code but one computer says its connected while the other
                    does not. the computer listening throws an exception saying it cant recieve
                    data when its not connected while the other computer says its
                    connected....he res the code, thanks for all your help

                    Imports System.Net.Sock ets
                    Imports System.Net

                    Public Class Form1
                    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.
                    InitializeCompo nent()

                    'Add any initialization after the InitializeCompo nent() 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.Disp ose()
                    End If
                    End If
                    MyBase.Dispose( disposing)
                    End Sub

                    'Required by the Windows Form Designer
                    Private components As System.Componen tModel.IContain er

                    '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 btnconnect As System.Windows. Forms.Button
                    Friend WithEvents txtport As System.Windows. Forms.TextBox
                    Friend WithEvents txtIP As System.Windows. Forms.TextBox
                    Friend WithEvents btnlisten As System.Windows. Forms.Button
                    Friend WithEvents txtlistenport As System.Windows. Forms.TextBox
                    Friend WithEvents GroupBox1 As System.Windows. Forms.GroupBox
                    Friend WithEvents GroupBox2 As System.Windows. Forms.GroupBox
                    Friend WithEvents rtbinfo As System.Windows. Forms.RichTextB ox
                    Friend WithEvents rtbsend As System.Windows. Forms.RichTextB ox
                    Friend WithEvents btnsend As System.Windows. Forms.Button
                    Friend WithEvents txtsend As System.Windows. Forms.TextBox
                    Friend WithEvents btndisconnect As System.Windows. Forms.Button
                    <System.Diagnos tics.DebuggerSt epThrough()> Private Sub
                    InitializeCompo nent()
                    Me.btnconnect = New System.Windows. Forms.Button
                    Me.txtport = New System.Windows. Forms.TextBox
                    Me.txtIP = New System.Windows. Forms.TextBox
                    Me.btnlisten = New System.Windows. Forms.Button
                    Me.txtlistenpor t = New System.Windows. Forms.TextBox
                    Me.GroupBox1 = New System.Windows. Forms.GroupBox
                    Me.btndisconnec t = New System.Windows. Forms.Button
                    Me.GroupBox2 = New System.Windows. Forms.GroupBox
                    Me.rtbinfo = New System.Windows. Forms.RichTextB ox
                    Me.rtbsend = New System.Windows. Forms.RichTextB ox
                    Me.btnsend = New System.Windows. Forms.Button
                    Me.txtsend = New System.Windows. Forms.TextBox
                    Me.GroupBox1.Su spendLayout()
                    Me.GroupBox2.Su spendLayout()
                    Me.SuspendLayou t()
                    '
                    'btnconnect
                    '
                    Me.btnconnect.L ocation = New System.Drawing. Point(16, 56)
                    Me.btnconnect.N ame = "btnconnect "
                    Me.btnconnect.T abIndex = 0
                    Me.btnconnect.T ext = "Connect"
                    '
                    'txtport
                    '
                    Me.txtport.Loca tion = New System.Drawing. Point(112, 56)
                    Me.txtport.Name = "txtport"
                    Me.txtport.Size = New System.Drawing. Size(56, 20)
                    Me.txtport.TabI ndex = 1
                    Me.txtport.Text = "5190"
                    '
                    'txtIP
                    '
                    Me.txtIP.Locati on = New System.Drawing. Point(32, 24)
                    Me.txtIP.Name = "txtIP"
                    Me.txtIP.TabInd ex = 2
                    Me.txtIP.Text = "IP"
                    '
                    'btnlisten
                    '
                    Me.btnlisten.Lo cation = New System.Drawing. Point(24, 48)
                    Me.btnlisten.Na me = "btnlisten"
                    Me.btnlisten.Ta bIndex = 3
                    Me.btnlisten.Te xt = "Listen"
                    '
                    'txtlistenport
                    '
                    Me.txtlistenpor t.Location = New System.Drawing. Point(120, 48)
                    Me.txtlistenpor t.Name = "txtlistenp ort"
                    Me.txtlistenpor t.Size = New System.Drawing. Size(56, 20)
                    Me.txtlistenpor t.TabIndex = 4
                    Me.txtlistenpor t.Text = "5190"
                    '
                    'GroupBox1
                    '
                    Me.GroupBox1.Co ntrols.Add(Me.t xtport)
                    Me.GroupBox1.Co ntrols.Add(Me.t xtIP)
                    Me.GroupBox1.Co ntrols.Add(Me.b tnconnect)
                    Me.GroupBox1.Co ntrols.Add(Me.b tndisconnect)
                    Me.GroupBox1.Lo cation = New System.Drawing. Point(8, 8)
                    Me.GroupBox1.Na me = "GroupBox1"
                    Me.GroupBox1.Si ze = New System.Drawing. Size(208, 88)
                    Me.GroupBox1.Ta bIndex = 5
                    Me.GroupBox1.Ta bStop = False
                    Me.GroupBox1.Te xt = "Connect"
                    '
                    'btndisconnect
                    '
                    Me.btndisconnec t.Location = New System.Drawing. Point(16, 56)
                    Me.btndisconnec t.Name = "btndisconn ect"
                    Me.btndisconnec t.TabIndex = 9
                    Me.btndisconnec t.Text = "Disconnect "
                    Me.btndisconnec t.Visible = False
                    '
                    'GroupBox2
                    '
                    Me.GroupBox2.Co ntrols.Add(Me.b tnlisten)
                    Me.GroupBox2.Co ntrols.Add(Me.t xtlistenport)
                    Me.GroupBox2.Lo cation = New System.Drawing. Point(8, 104)
                    Me.GroupBox2.Na me = "GroupBox2"
                    Me.GroupBox2.Si ze = New System.Drawing. Size(208, 88)
                    Me.GroupBox2.Ta bIndex = 0
                    Me.GroupBox2.Ta bStop = False
                    Me.GroupBox2.Te xt = "Listen"
                    '
                    'rtbinfo
                    '
                    Me.rtbinfo.Loca tion = New System.Drawing. Point(16, 200)
                    Me.rtbinfo.Name = "rtbinfo"
                    Me.rtbinfo.Read Only = True
                    Me.rtbinfo.Size = New System.Drawing. Size(208, 152)
                    Me.rtbinfo.TabI ndex = 6
                    Me.rtbinfo.Text = ""
                    '
                    'rtbsend
                    '
                    Me.rtbsend.Loca tion = New System.Drawing. Point(256, 184)
                    Me.rtbsend.Name = "rtbsend"
                    Me.rtbsend.Size = New System.Drawing. Size(296, 168)
                    Me.rtbsend.TabI ndex = 7
                    Me.rtbsend.Text = ""
                    '
                    'btnsend
                    '
                    Me.btnsend.Loca tion = New System.Drawing. Point(320, 40)
                    Me.btnsend.Name = "btnsend"
                    Me.btnsend.TabI ndex = 3
                    Me.btnsend.Text = "Send"
                    '
                    'txtsend
                    '
                    Me.txtsend.Loca tion = New System.Drawing. Point(320, 72)
                    Me.txtsend.Name = "txtsend"
                    Me.txtsend.TabI ndex = 8
                    Me.txtsend.Text = "TextBox1"
                    '
                    'Form1
                    '
                    Me.AutoScaleBas eSize = New System.Drawing. Size(5, 13)
                    Me.ClientSize = New System.Drawing. Size(560, 357)
                    Me.Controls.Add (Me.txtsend)
                    Me.Controls.Add (Me.rtbsend)
                    Me.Controls.Add (Me.GroupBox1)
                    Me.Controls.Add (Me.GroupBox2)
                    Me.Controls.Add (Me.rtbinfo)
                    Me.Controls.Add (Me.btnsend)
                    Me.Name = "Form1"
                    Me.Text = "Form1"
                    Me.GroupBox1.Re sumeLayout(Fals e)
                    Me.GroupBox2.Re sumeLayout(Fals e)
                    Me.ResumeLayout (False)

                    End Sub

                    #End Region

                    #Region "Declaratio ns"

                    Dim homeip As Net.IPAddress
                    Dim ClientSocket As Net.Sockets.Soc ket
                    Dim ASCII As New System.Text.ASC IIEncoding

                    Dim ListenSocket As Net.Sockets.Soc ket

                    #End Region

                    #Region "Connect"

                    Private Sub Form1_Load(ByVa l sender As System.Object, ByVal e As
                    System.EventArg s) Handles MyBase.Load

                    homeip =
                    Net.Dns.GetHost ByName(Net.Dns. GetHostName).Ad dressList.GetVa lue(0)

                    Me.Text = homeip.ToString

                    End Sub

                    Private Sub btnconnect_Clic k(ByVal sender As System.Object, ByVal e As
                    System.EventArg s) Handles btnconnect.Clic k

                    Dim addr As Net.IPAddress =
                    Net.Dns.Resolve (Me.txtIP.Text) .AddressList(0)

                    If Not addr Is Nothing Then
                    'Create IP endpoint
                    Dim EP As New Net.IPEndPoint( addr, CInt(Me.txtport .Text))

                    'create socket
                    ClientSocket = New
                    Net.Sockets.Soc ket(Net.Sockets .AddressFamily. InterNetwork,
                    Net.Sockets.Soc ketType.Stream, Net.Sockets.Pro tocolType.Tcp)

                    'Connect
                    ClientSocket.Be ginConnect(EP, AddressOf ConnectCallBack , Nothing)
                    ' ClientSocket.Se nd(

                    End If

                    End Sub

                    Private Sub ConnectCallBack (ByVal ar As IAsyncResult)

                    Try
                    ClientSocket.En dConnect(ar)

                    Dim dlg As New NoParamsDelegat e(AddressOf ConnectedUI)

                    Me.Invoke(dlg)

                    'Begin Receiveing Data
                    Dim bytes(4095) As Byte
                    ClientSocket.Be ginReceive(byte s, 0, bytes.Length,
                    SocketFlags.Non e, AddressOf ReceiveCallBack , bytes)

                    Catch ex As Exception
                    Me.rtbinfo.Text += vbNewLine & ex.Message & vbNewLine
                    End Try

                    End Sub

                    Private Delegate Sub NoParamsDelegat e()

                    Private Sub ConnectedUI()

                    Me.rtbinfo.Text += vbNewLine & "Connected" & vbNewLine

                    Me.btnsend.Enab led = True
                    Me.rtbsend.Focu s()

                    End Sub

                    Private Sub DisconnectedUI( )

                    Me.rtbinfo.Text += vbNewLine & "Disconnect ed" & vbNewLine

                    Me.btnconnect.V isible = True
                    Me.btndisconnec t.Visible = False
                    Me.btnsend.Enab led = False
                    Me.btnconnect.F ocus()

                    End Sub

                    Private Sub ReceiveCallBack (ByVal ar As IAsyncResult)

                    Dim bytes() As Byte = CType(ar.AsyncS tate, Byte())
                    Dim numbytes As Int32 = ClientSocket.En dReceive(ar)

                    If numbytes = 0 Then
                    ClientSocket.Sh utdown(SocketSh utdown.Both)
                    ClientSocket.Cl ose()

                    Dim dlg As New NoParamsDelegat e(AddressOf DisconnectedUI)

                    Me.Invoke(dlg)
                    Else
                    Dim recv As String = ASCII.GetString (bytes, 0, numbytes)

                    'Clear the buffer
                    Array.Clear(byt es, 0, bytes.Length)

                    'Show in UI
                    Dim dlg As New OneStringDelega te(AddressOf DisplayReceived Data)
                    Dim args() As Object = {recv}

                    Me.Invoke(dlg, args)

                    'Begin Receive Again
                    ClientSocket.Be ginReceive(byte s, 0, bytes.Length,
                    SocketFlags.Non e, AddressOf ReceiveCallBack , bytes)

                    End If

                    End Sub

                    Private Delegate Sub OneStringDelega te(ByVal data As String)

                    Private Sub btnsend_Click(B yVal sender As System.Object, ByVal e As
                    System.EventArg s) Handles btnsend.Click

                    Try
                    If sender Is ClientSocket Then
                    Dim bytes() As Byte = ASCII.GetBytes( Me.txtsend.Text )
                    ClientSocket.Se nd(bytes)
                    ElseIf sender Is ListenSocket Then
                    Dim bytes() As Byte = ASCII.GetBytes( Me.txtsend.Text )
                    ListenSocket.Se nd(bytes)
                    End If
                    Catch ex As Exception
                    Me.rtbinfo.Text += vbNewLine & ex.Message & vbNewLine
                    End Try

                    End Sub

                    #End Region

                    #Region "Listen"

                    Private Sub btnlisten_Click (ByVal sender As System.Object, ByVal e As
                    System.EventArg s) Handles btnlisten.Click

                    Me.btndisconnec t.Visible = True
                    Me.btnconnect.V isible = False
                    Call Listen(homeip, Me.txtlistenpor t.Text)

                    End Sub

                    Private Sub Listen(ByVal IP As IPAddress, ByVal port As Integer)

                    Dim ep As New Net.IPEndPoint( IP, port)

                    ListenSocket = New Net.Sockets.Soc ket(AddressFami ly.InterNetwork ,
                    SocketType.Stre am, ProtocolType.Tc p)
                    ListenSocket.Bi nd(ep)
                    ListenSocket.Li sten(50)
                    ListenSocket.Be ginAccept(Addre ssOf ListenCallBack, Nothing)

                    End Sub

                    Private Sub ListenCallBack( ByVal ar As IAsyncResult)

                    Try

                    ListenSocket.En dAccept(ar)

                    'Begin Receiveing Data
                    Dim bytes(4095) As Byte
                    ListenSocket.Be ginReceive(byte s, 0, bytes.Length,
                    SocketFlags.Non e, AddressOf ListenReceiveCa llBack, bytes)

                    Catch ex As Exception
                    Me.rtbinfo.Text += vbNewLine & ex.Message & vbNewLine
                    End Try

                    End Sub

                    Private Sub ListenReceiveCa llBack(ByVal ar As IAsyncResult)

                    Dim bytes() As Byte = CType(ar.AsyncS tate, Byte())
                    Dim numbytes As Int32 = ListenSocket.En dReceive(ar)

                    If numbytes = 0 Then

                    ListenSocket.Sh utdown(SocketSh utdown.Both)
                    ListenSocket.Cl ose()

                    Else

                    Dim recv As String = ASCII.GetString (bytes, 0, numbytes)

                    'Clear the buffer
                    Array.Clear(byt es, 0, bytes.Length)

                    'Begin Receive Again
                    ListenSocket.Be ginReceive(byte s, 0, bytes.Length,
                    SocketFlags.Non e, AddressOf ListenReceiveCa llBack, bytes)

                    End If

                    End Sub

                    #End Region


                    Private Sub DisplayReceived Data(ByVal data As String)

                    With Me.rtbsend

                    .SelectionStart = .Text.Length
                    .SelectedText = data

                    End With

                    End Sub

                    End Class

                    Comment

                    • iwdu15

                      #11
                      Re: TCPListener

                      ok, this is driving me crazy, i get this error on my comp :

                      A request to send or receive data was disallowed because the socket is not
                      connected and (when sending on a datagram socket using a sendto call) no
                      address was supplied

                      and a false connection state while the other comp has a "true" connection
                      state and says its connected....wt f is going on!!! lol

                      Comment

                      • Dragon

                        #12
                        Re: TCPListener

                        Okay, point #1 done. Now let's move on #3 & #4 8=].
                        It seems that you misunderstand how the listening works.

                        The Socket.EndAccep t() (.Accept()) method returns a *new* socket. This
                        new socket is *connected* to another computer and is used to
                        send/receive data. First socket is still *listening* and can be used to
                        accept new connections; if you don't want them, call it's .Close()
                        method. You can't call .Receive() on first socket, because it *is not*
                        connected.

                        See my pre-pre-previous response, points #3, #4.

                        Roman


                        Comment

                        • iwdu15

                          #13
                          Re: TCPListener

                          ooohhhhh....tha t makes so much more sense, so then in order to send data to
                          the other computer do i create a new socket and just call the "begin send"
                          method? will the second socket already be connected? thanks for all your help

                          Comment

                          • Wicksy

                            #14
                            Re: TCPListener

                            You dont need to create a new socket...
                            One was created for you and returned by the ListenSocket.Be ginAccept()
                            method.
                            eg. (quick & dirty):

                            dim x as Socket
                            x = ListenSocket.Be ginAccept() ' will assign a new socket to x

                            You can now use x to send/receive. Your ListenSocket is also still there,
                            listening away.
                            Usually for a synchronous server application you put the whole lot in a
                            continuous loop:

                            while true

                            dim x as Socket
                            x = ListenSocket.Ac cept() ' will assign a new socket to x

                            'do stuff with x
                            x.close()

                            end while


                            HTH.


                            "iwdu15" <iwdu15@discuss ions.microsoft. com> wrote in message
                            news:3E8D4D68-A21B-481A-9666-386E913F0469@mi crosoft.com...[color=blue]
                            > ooohhhhh....tha t makes so much more sense, so then in order to send data
                            > to
                            > the other computer do i create a new socket and just call the "begin send"
                            > method? will the second socket already be connected? thanks for all your
                            > help[/color]


                            Comment

                            • iwdu15

                              #15
                              Re: TCPListener

                              ok that helps alot, thanks, but what about the clientsocket that tried to
                              connect to the listening socket, does that one create a new socket too?
                              thanks for your help

                              Comment

                              Working...