无法将TcpClient连接到TcpListener Visual Basic .NET

时间:2017-03-24 08:25:12

标签: .net vb.net sockets tcp tcpclient

我'努力创建TCP服务器和客户端。我有很多教程,如herehere。但仍然无法成功!

这是我的代码:

Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Runtime.InteropServices

Public Class Form1

Private Server As TcpListener = Nothing
Private ServerThread As Thread = Nothing
Private WithEvents Tray As New NotifyIcon
Private myClient As TcpClient = Nothing
Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.115")


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Shown
    Server = New TcpListener(localAddr, 40000)
    ServerThread = New Thread(AddressOf ConnectionListener)
    ServerThread.IsBackground = True
    ServerThread.Start()
    TextBox1.Text = "Server is ready!"

' function I use to get all the TCP clients I can see in local web. 
' You can find it by the first link (see at the top of the post)
    lbComputers.DataSource = GetNetworkComputers() 

End Sub

Private Sub ConnectionListener()
    Try
        Server.Start()
        While True
            myClient = Server.AcceptTcpClient
            'myClient.Connect("MSK4", 40000) 'tried this: didn't work
            Dim T As New Thread(AddressOf SomeClientActions)
            T.Start(myClient)
            TextBox2.Text = "Client connected" ' It's always empty :(

            End While



            myClient.Close()
        End While

    Catch ex As Exception
        MessageBox.Show("Unable to Accept Connections", "Server Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    End Try
    Application.ExitThread()

End Sub

Private Sub SomeClientActions(ByVal client As Object)
    ' ... do something with "client" in here ...
    Invoke(Sub() TextBox2.Text = "This text is never appears :(")
End Sub


Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
    'myClient.Close() 'error is here
    Server.Stop()
End Sub

End Class

我有两个TextBox(TextBox1和TextBox2)。我在第一个中得到Server is ready!但在第二个中得不到任何东西!所以我想我无法连接到我的服务器!此行后面的代码:

myClient = Server.AcceptTcpClient

永远不会执行。 我试着用

myClient.Connect("MSK4", 40000)

由于我的计算机名称是MSK4,但后来我得到了我的异常和MessageBox。 如何实现连接?我做错了什么?

1 个答案:

答案 0 :(得分:1)

让服务器收听127.0.0.115表示它只接受来自该特定IP的连接 。要侦听来自任何IP的连接,您需要指定0.0.0.0IPAddress.Any

至于建立连接,你必须只使用IP地址,计算机名称不会起作用。