Results 1 to 15 of 15

Thread: How to stop connection rejection

  1. #1

    Thread Starter
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    How to stop connection rejection

    I get an error saying that the connection was rejected by the target machine here, suggesting that my firewall is working well

    How do I make sure that the connection is accepted? It's a chat program (obviously) so I'm going to need to do the same thing on users' computers when it is installed. How do I make this in such a way that the connection will be accepted but leaving security uncomprimised?
    vb.net Code:
    1. Imports System.Net.Sockets
    2. Public Class QuickChat
    3.     'Dim invited As List(Of String) = New List(Of String) 'ip addresses
    4.     Dim ip(3) As Byte
    5.     Dim conn As NetworkStream
    6.     'Dim s As Socket
    7.     Dim tcpclient As TcpClient
    8.     'Dim tcplistener As TcpListener
    9.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    10.         'Set up form
    11.         Dim si As Size = Screen.GetWorkingArea(New Point(1, 1)).Size
    12.         Me.MaximumSize = New Size(si.Width \ 3, si.Height)
    13.         Me.Width = Me.MaximumSize.Width
    14.         'Retrieve chat IP.
    15.         Dim ipre As New System.Text.RegularExpressions.Regex("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
    16.         Dim cip As String = InputBox("Please enter the IP address of the person that you would like to send to.", "Enter IP Address", "0.0.0.0")
    17.         If Not ipre.IsMatch(cip) Then
    18.             Me.Close()
    19.             Exit Sub
    20.         End If
    21.         Dim ipbs() As String = cip.Split(".")
    22.         ip(0) = CByte(ipbs(0))
    23.         ip(1) = CByte(ipbs(1))
    24.         ip(2) = CByte(ipbs(2))
    25.         ip(3) = CByte(ipbs(3))
    26.         'Set up send/recieve
    27.         tcpclient = New TcpClient()
    28.         tcpclient.Connect(New Net.IPAddress(ip), 120)
    29.         conn = tcpclient.GetStream()
    30.         Me.tmrCheckForMessage.Start()
    31.     End Sub
    32.  
    33.     Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
    34.         SendMsg(Me.txtNewMessage.Text)
    35.     End Sub
    36.     Private Sub SendMsg(ByVal msg As String)
    37.         Dim c As Char
    38.         For Each c In msg
    39.             conn.WriteByte(AscW(c))
    40.         Next
    41.         conn.WriteByte(0)
    42.     End Sub
    43.     Private Function GetMsgIfAny() As String
    44.         Dim b As Byte = conn.ReadByte()
    45.         Dim str As String = ""
    46.         While b > 0
    47.             str &= ChrW(b)
    48.             b = conn.ReadByte()
    49.         End While
    50.         Return str
    51.     End Function
    52.  
    53.     Private Sub tmrCheckForMessage_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrCheckForMessage.Tick
    54.         Dim s As String = GetMsgIfAny()
    55.         If s = "" Then Exit Sub
    56.         Me.txtChatLog.Text &= String.Format("{0}{1}{0}{0}", ControlChars.CrLf, s)
    57.     End Sub
    58. End Class

  2. #2

    Thread Starter
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: How to stop connection rejection

    oh my gosh, I'm an idiot...
    use the TCP port 445 and it works.

    But don't worry, there's still a problem...
    The ReadByte() call freezes the app if there's no data coming in, even though it's running on a different thread. (Same thing with SerialPorts.) Why is this, and how do I fix it?

  3. #3

    Thread Starter
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: How to stop connection rejection

    Ok, I looked it up online and I used the TcpListener object instead. Now, on line 15, it says "you have attempted to access a socket in a way forbidden by its access permissions." WHY???

    vb.net Code:
    1. Imports System.Net.Sockets
    2. Public Class Form1
    3.     Dim currentstr() As Byte
    4.     'Dim invited As List(Of String) = New List(Of String) 'ip addresses
    5.     Dim ip(3) As Byte
    6.     Dim conn As NetworkStream
    7.     'Dim s As Socket
    8.     Dim tcpclient As TcpClient
    9.     Dim tcplistener As TcpListener
    10.     Dim listenert As Threading.Thread = New Threading.Thread(AddressOf TcpListen)
    11.     Dim isclosing As Boolean = False
    12.     Delegate Sub NCDeleg(ByVal txtadd As String)
    13.     Dim ncinvoke As NCDeleg = New NCDeleg(AddressOf NotifyConn)
    14.     Private Sub TcpListen()
    15.         [B]tcplistener.Start()[/B]
    16.         While Not isclosing
    17.             If tcplistener.Pending() Then
    18.                 Dim rs As NetworkStream = tcplistener.AcceptTcpClient().GetStream()
    19.                 Dim b As Byte = rs.ReadByte
    20.                 Dim str As String = ""
    21.                 While b > 0
    22.                     str &= ChrW(b)
    23.                     b = rs.ReadByte()
    24.                 End While
    25.                 Me.Invoke(ncinvoke, str)
    26.             End If
    27.             Threading.Thread.Sleep(500)
    28.         End While
    29.         tcplistener.Stop()
    30.     End Sub
    31.     Private Sub NotifyConn(ByVal txtadd As String)
    32.         Me.txtChatLog.Text &= String.Format("{0}{1}{0}{0}", ControlChars.CrLf, txtadd)
    33.     End Sub
    34.  
    35.     Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    36.         isclosing = True
    37.         listenert.Join()
    38.     End Sub
    39.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    40.         'Set up form
    41.         Dim si As Size = Screen.GetWorkingArea(New Point(1, 1)).Size
    42.         Me.MaximumSize = New Size(si.Width \ 3, si.Height)
    43.         Me.Width = Me.MaximumSize.Width
    44.         'Retrieve chat IP.
    45.         Dim ipre As New System.Text.RegularExpressions.Regex("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
    46.         Dim cip As String = InputBox("Please enter the IP address of the person that you would like to send to.", "Enter IP Address", "0.0.0.0")
    47.         If Not ipre.IsMatch(cip) Then
    48.             Me.Close()
    49.             Exit Sub
    50.         End If
    51.         Dim ipbs() As String = cip.Split(".")
    52.         ip(0) = CByte(ipbs(0))
    53.         ip(1) = CByte(ipbs(1))
    54.         ip(2) = CByte(ipbs(2))
    55.         ip(3) = CByte(ipbs(3))
    56.         ''Set up sockets
    57.         's = New Socket(AddressFamily.DataLink, SocketType.Stream, ProtocolType.Tcp)
    58.         's.Connect(New Net.IPAddress(ip), 120)
    59.         'conn = New NetworkStream(s, IO.FileAccess.ReadWrite, True)
    60.         tcpclient = New TcpClient()
    61.         Try
    62.             tcpclient.Connect(New Net.IPAddress(ip), 445)
    63.         Catch ex As SocketException
    64.             MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    65.             Me.Close()
    66.             Exit Sub
    67.         End Try
    68.         'tcplistener = New TcpListener(New Net.IPAddress(ip), 120)
    69.         conn = tcpclient.GetStream()
    70.         'conn.ReadTimeout = 10
    71.         tcplistener = New TcpListener(New Net.IPAddress(ip), 445)
    72.         listenert.Start()
    73.         'Me.tmrCheckForMessage.Start()
    74.     End Sub
    75.  
    76.     'Private Sub btnInvite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInvite.Click
    77.     '    Dim ip As New System.Text.RegularExpressions.Regex("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
    78.     '    Dim val As String = InputBox("Please enter the IP address of the person that you would like to send to.", "Enter IP Address", "0.0.0.0")
    79.     '    If Not ip.IsMatch(val) Then
    80.     '        If val = "" Then Exit Sub
    81.     '        MessageBox.Show("Invalid IP address.", "Invalid IP", MessageBoxButtons.OK, MessageBoxIcon.Error)
    82.     '        Exit Sub
    83.     '    End If
    84.     '    invited.Add(val)
    85.     'End Sub
    86.  
    87.     Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
    88.         SendMsg(Me.txtNewMessage.Text)
    89.         Me.txtNewMessage.Text = ""
    90.     End Sub
    91.     Private Sub SendMsg(ByVal msg As String)
    92.         Dim c As Char
    93.         For Each c In msg
    94.             conn.WriteByte(AscW(c))
    95.         Next
    96.         conn.WriteByte(0)
    97.     End Sub
    98.     '    Private Function GetMsgIfAny() As String
    99.     '        On Error GoTo sub_exit
    100.     '        Dim b As Byte = conn.ReadByte()
    101.     '        Dim str As String = ""
    102.     '        While b > 0
    103.     '            str &= ChrW(b)
    104.     '            b = conn.ReadByte()
    105.     '        End While
    106.     '        Return str
    107.     'sub_exit:
    108.     '        GetMsgIfAny = ""
    109.     '    End Function
    110.     'Private Sub GetAsyncMsg(ByVal ia As IAsyncResult)
    111.     '    If ia.IsCompleted Then
    112.  
    113.     '    End If
    114.     'End Sub
    115.  
    116.     'Private Sub tmrCheckForMessage_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrCheckForMessage.Tick
    117.     '    Dim s As String = GetMsgIfAny()
    118.     '    If s = "" Then Exit Sub
    119.     '    Me.txtChatLog.Text &= String.Format("{0}{1}{0}{0}", ControlChars.CrLf, s)
    120.     '    conn.BeginRead(currentstr, 0, 1, AddressOf GetAsyncMsg, Nothing)
    121.     'End Sub
    122. End Class

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: How to stop connection rejection

    You say:
    even though it's running on a different thread
    but I see no sign of multiple threads there. The Timer.Tick event is raised on the UI thread so your tmrCheckForMessage_Tick event handler is executed on the UI thread. That's where you call GetMsgIfAny, so that's executed on the UI thread too, and that's where you call ReadByte, so that's executed on the UI thread too.

    The NetworkStream class already provides asynchronous methods so, if you want to read the data asynchronously, that's what you should use. You simply call BeginRead and pass a callback and then let it go. Your callback will be invoked when data becomes available so you read it there.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5

    Thread Starter
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: How to stop connection rejection

    I just added the extra thread. I can't use BeginRead because I don't know how many bytes I need to read.

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: How to stop connection rejection

    Quote Originally Posted by minitech View Post
    I just added the extra thread. I can't use BeginRead because I don't know how many bytes I need to read.
    I don't see why that would be an impediment to using BeginRead. Most people don't know how many bytes they need to read. You just keep reading until there are no bytes left to read, pretty much as you're doing now but you would Read in blocks instead of one byte at a time with ReadByte.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  7. #7

    Thread Starter
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: How to stop connection rejection

    How do you do that? BeginRead asks for the number of bytes to read. Does it automatically stop reading if there are no more?

  8. #8

    Thread Starter
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: How to stop connection rejection

    Ok, I've got it like this, but the message box never shows up.
    vb Code:
    1. Private Sub GetAsyncMsg(ByVal ia As IAsyncResult)
    2.         MessageBox.Show("Data recieved!!")
    3.         conn.BeginRead(currentstr, 0, currentstr.Length, AddressOf GetAsyncMsg, Nothing)
    4.     End Sub

  9. #9
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: How to stop connection rejection

    Quote Originally Posted by minitech View Post
    How do you do that? BeginRead asks for the number of bytes to read. Does it automatically stop reading if there are no more?
    Just pick a good size for a buffer, e.g. 1024, and read blocks of that size. You call BeginRead and let it go. Your callback will be invoked and you'll read a block of data up to the size specified. If the actual amount of data read is less than that you know that that's all the data there was to read. If the actual amount read is equal to the size of the buffer then either that's the exact amount of data there was or there's more to read, which you can determine from the DataAvailable property. Once you've read a block you simply call BeginRead again and your callback will be invoked again, either immediately if there is more data t read or else later, when more data becomes available.

    You might want to check out the documentation for the EndRead method for a simple example that you can then build on.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  10. #10

    Thread Starter
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: How to stop connection rejection

    Nothing doing, still not working.
    Is it something to do with the fact that I'm using the same connection for read/write and that the IP address that I entered is my own?

  11. #11
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: How to stop connection rejection

    As is always the case, when you're having trouble with one aspect of a project you should forget about the project for the time being. You should create a brand new project and test ONLY the functionality that you're having trouble with. By removing all other distractions you are able to concentrate on just that functionality and getting it to work. Once you've got it working, then you can worry about integrating it back into your original project.

    With that in mind, you should have done something like what I did:

    1. Create a new WinForms project.
    2. Add three Buttons to the form.
    3. Add the following code:
    Code:
    Imports System.Net.Sockets
    Imports System.Net
    Imports System.IO
    Imports System.Text
    
    Public Class Form1
    
        Private listener As New TcpListener(IPAddress.Parse("127.0.0.1"), 1234)
        Private server As TcpClient
        Private client As TcpClient
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Me.listener.Start()
            Me.listener.BeginAcceptTcpClient(AddressOf AcceptTcpClient, Me.listener)
        End Sub
    
        Private Sub AcceptTcpClient(ByVal ar As IAsyncResult)
            Me.server = Me.listener.EndAcceptTcpClient(ar)
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Me.client = New TcpClient()
            Me.client.Connect("127.0.0.1", 1234)
        End Sub
    
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
            Dim buffer As Byte() = Encoding.ASCII.GetBytes(InputBox("Enter the message to send:", "Send"))
    
            Me.client.GetStream().Write(buffer, 0, buffer.Length)
        End Sub
    
        Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
            Dim stream As NetworkStream = Me.server.GetStream()
            Dim buffer(16 - 1) As Byte
    
            stream.BeginRead(buffer, _
                             0, _
                             buffer.Length, _
                             AddressOf Read, _
                             New Object() {stream, _
                                           buffer})
        End Sub
    
        Private Sub Read(ByVal ar As IAsyncResult)
            Dim userState As Object() = DirectCast(ar.AsyncState, Object())
            Dim stream As NetworkStream = DirectCast(userState(0), NetworkStream)
            Dim bytesRead As Integer = stream.EndRead(ar)
            Dim buffer As Byte() = DirectCast(userState(1), Byte())
    
            Static message As String
    
            message &= Encoding.ASCII.GetString(buffer, 0, bytesRead)
    
            If bytesRead = buffer.Length AndAlso stream.DataAvailable Then
                stream.BeginRead(buffer, _
                                 0, _
                                 buffer.Length, _
                                 AddressOf Read, _
                                 New Object() {stream, _
                                               buffer})
            Else
                MessageBox.Show(message, "Receive")
                message = Nothing
            End If
        End Sub
    
    End Class
    4. Run the project.
    5. Click Button1 to make the connection.
    6. Click Button2 and enter the message to send.
    7. Click Button3 to read the message received.

    You'll see that, even though only 16 bytes are being read at a time, the entire message is received and displayed, no matter how long it is.
    Last edited by jmcilhinney; Sep 24th, 2009 at 01:05 AM.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  12. #12

    Thread Starter
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: How to stop connection rejection

    Ok. It works. But when I put it into my code, on the line that says "tcplistener.Start()", it says that it was accessed in a way forbidden by its access permissions. It's in Form_Load, just like your example. I tried it out with my IP and 127.0.0.1. Nothing works.

  13. #13

    Thread Starter
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: How to stop connection rejection

    I took out the tmrCheckForMessages.Start() line, and it started working. There was nothing in its event handler. Why did it start working all of a sudden like that?

    There's only one more problem. It prints the first character, then the rest of the message. Why does that happen?

    vb.net Code:
    1. Imports System.Net.Sockets
    2. Public Class Form1
    3.     Dim currentstr(0) As Byte
    4.     Dim conn As NetworkStream
    5.     Dim tcpclient As TcpClient
    6.     Dim tcprecieve As TcpClient
    7.     Dim tcplistener As TcpListener
    8.     Dim inconn As NetworkStream
    9.     Delegate Sub NotifyDeleg(ByVal txt As String)
    10.     Dim ndinvoke As NotifyDeleg = New NotifyDeleg(AddressOf NotifyConn)
    11.     Private Sub NotifyConn(ByVal txtadd As String)
    12.         Me.txtChatLog.Text &= String.Format("{0}Chatter said:{0}{0}{1}{0}{0}", ControlChars.CrLf, txtadd)
    13.     End Sub
    14.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    15.         'Set up form
    16.         Dim si As Size = Screen.GetWorkingArea(New Point(1, 1)).Size
    17.         Me.MaximumSize = New Size(si.Width \ 3, si.Height)
    18.         Me.Width = Me.MaximumSize.Width
    19.         'Retrieve chat IP.
    20.         Dim ipre As New System.Text.RegularExpressions.Regex("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
    21.         Dim cip As String = InputBox("Please enter the IP address of the person that you would like to send to.", "Enter IP Address", "0.0.0.0")
    22.         If Not ipre.IsMatch(cip) Then
    23.             Me.Close()
    24.             Exit Sub
    25.         End If
    26.         Me.txtChatLog.Text = "Begin chat with computer " & cip & ControlChars.CrLf
    27.         tcpclient = New TcpClient()
    28.         tcplistener = New TcpListener(Net.IPAddress.Parse(cip), 1234)
    29.         tcplistener.Start()
    30.         tcplistener.BeginAcceptTcpClient(AddressOf AcceptTcpClient, Nothing)
    31.         Try
    32.             tcpclient.Connect(Net.IPAddress.Parse(cip), 1234)
    33.             conn = tcpclient.GetStream()
    34.         Catch ex As SocketException
    35.             MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    36.             Me.Close()
    37.             Exit Sub
    38.         End Try
    39.     End Sub
    40. #Region "Callbacks"
    41.     Private Sub AcceptTcpClient(ByVal ia As IAsyncResult)
    42.         tcprecieve = tcplistener.EndAcceptTcpClient(ia)
    43.         inconn = tcprecieve.GetStream()
    44.         Dim buf(1023) As Byte
    45.         inconn.BeginRead(buf, 0, buf.Length - 1, AddressOf AcceptData, buf)
    46.     End Sub
    47.     Private Sub AcceptData(ByVal ia As IAsyncResult)
    48.         Dim buf() As Byte = DirectCast(ia.AsyncState, Byte())
    49.         Dim str As String = System.Text.Encoding.ASCII.GetString(buf)
    50.         Me.Invoke(ndinvoke, str)
    51.         inconn.BeginRead(buf, 0, buf.Length - 1, AddressOf AcceptData, buf)
    52.     End Sub
    53. #End Region
    54.  
    55.     Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
    56.         SendMsg(Me.txtNewMessage.Text)
    57.         Me.txtNewMessage.Text = ""
    58.     End Sub
    59.     Private Sub SendMsg(ByVal msg As String)
    60.         Try
    61.             Dim c As Char
    62.             For Each c In msg
    63.                 conn.WriteByte(AscW(c))
    64.             Next
    65.             Me.txtChatLog.Text &= String.Format("{0}You said:{0}{0}{1}{0}{0}", ControlChars.CrLf, msg)
    66.         Catch ex As SocketException
    67.             MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    68.             Me.Close()
    69.             Exit Sub
    70.         End Try
    71.     End Sub
    72. End Class

  14. #14
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: How to stop connection rejection

    I'll start of with a suggestion coding style. I look at that big chunk of code you posted and I find it very hard to read. I tend to use lots of blank lines in my code to separate logical chunks of code and, in my opinion, it makes the code much easier to look at. I would suggest that you, and anyone else, do the same, e.g.
    vb.net Code:
    1. Imports System.Net.Sockets
    2.  
    3. Public Class Form1
    4.  
    5.     Dim currentstr(0) As Byte
    6.     Dim conn As NetworkStream
    7.     Dim tcpclient As TcpClient
    8.     Dim tcprecieve As TcpClient
    9.     Dim tcplistener As TcpListener
    10.     Dim inconn As NetworkStream
    11.  
    12.     Delegate Sub NotifyDeleg(ByVal txt As String)
    13.  
    14.     Dim ndinvoke As NotifyDeleg = New NotifyDeleg(AddressOf NotifyConn)
    15.  
    16.     Private Sub NotifyConn(ByVal txtadd As String)
    17.         Me.txtChatLog.Text &= String.Format("{0}Chatter said:{0}{0}{1}{0}{0}", ControlChars.CrLf, txtadd)
    18.     End Sub
    19.  
    20.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    21.         'Set up form
    22.         Dim si As Size = Screen.GetWorkingArea(New Point(1, 1)).Size
    23.  
    24.         Me.MaximumSize = New Size(si.Width \ 3, si.Height)
    25.         Me.Width = Me.MaximumSize.Width
    26.  
    27.         'Retrieve chat IP.
    28.         Dim ipre As New System.Text.RegularExpressions.Regex("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
    29.         Dim cip As String = InputBox("Please enter the IP address of the person that you would like to send to.", "Enter IP Address", "0.0.0.0")
    30.  
    31.         If Not ipre.IsMatch(cip) Then
    32.             Me.Close()
    33.             Exit Sub
    34.         End If
    35.  
    36.         Me.txtChatLog.Text = "Begin chat with computer " & cip & ControlChars.CrLf
    37.         tcpclient = New TcpClient()
    38.         tcplistener = New TcpListener(Net.IPAddress.Parse(cip), 1234)
    39.         tcplistener.Start()
    40.         tcplistener.BeginAcceptTcpClient(AddressOf AcceptTcpClient, Nothing)
    41.  
    42.         Try
    43.             tcpclient.Connect(Net.IPAddress.Parse(cip), 1234)
    44.             conn = tcpclient.GetStream()
    45.         Catch ex As SocketException
    46.             MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    47.             Me.Close()
    48.             Exit Sub
    49.         End Try
    50.     End Sub
    51.  
    52. #Region "Callbacks"
    53.  
    54.     Private Sub AcceptTcpClient(ByVal ia As IAsyncResult)
    55.         tcprecieve = tcplistener.EndAcceptTcpClient(ia)
    56.         inconn = tcprecieve.GetStream()
    57.  
    58.         Dim buf(1023) As Byte
    59.  
    60.         inconn.BeginRead(buf, 0, buf.Length - 1, AddressOf AcceptData, buf)
    61.     End Sub
    62.  
    63.     Private Sub AcceptData(ByVal ia As IAsyncResult)
    64.         Dim buf() As Byte = DirectCast(ia.AsyncState, Byte())
    65.         Dim str As String = System.Text.Encoding.ASCII.GetString(buf)
    66.  
    67.         Me.Invoke(ndinvoke, str)
    68.         inconn.BeginRead(buf, 0, buf.Length - 1, AddressOf AcceptData, buf)
    69.     End Sub
    70.  
    71. #End Region
    72.  
    73.     Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
    74.         SendMsg(Me.txtNewMessage.Text)
    75.         Me.txtNewMessage.Text = ""
    76.     End Sub
    77.  
    78.     Private Sub SendMsg(ByVal msg As String)
    79.         Try
    80.             Dim c As Char
    81.  
    82.             For Each c In msg
    83.                 conn.WriteByte(AscW(c))
    84.             Next
    85.  
    86.             Me.txtChatLog.Text &= String.Format("{0}You said:{0}{0}{1}{0}{0}", ControlChars.CrLf, msg)
    87.         Catch ex As SocketException
    88.             MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    89.             Me.Close()
    90.             Exit Sub
    91.         End Try
    92.     End Sub
    93.  
    94. End Class
    I don't know about you, but I find that to be far less of an assault on the senses than the solid block you posted. Sure the code takes up more lines that way but that's what we have scroll bars for. Obviously it's up to you what you do but you'll be doing me at least a big favour if you adopt that style, and others to I think, and yourself.

    Anyway, on to the question at hand. I'm going to make an educated guess and say that you're sending the data character by character instead of sending the entire message together. Why use Encoding.GetString at the receiving end and not use Encoding.GetBytes at the sending end?
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  15. #15

    Thread Starter
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: How to stop connection rejection

    Until you posted that code, I had no idea that it existed. Sure, I'll do that.

    About the coding style:
    Usually I do it better, but I rewrote this one so many times, commented out lots of things, removed them, etc., and it kind of became a mess. Next time I post, it will probably be neater.

Tags for this Thread

Posting Permissions

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



Click Here to Expand Forum to Full Width