在Linux上使用VB.net的Windows TCP套接字连接

时间:2017-07-07 15:48:27

标签: linux vb.net sockets tcp

目标是Windows和Linux之间的vb.net连接。

windows-server(vb.net):服务器应该在端口4001 / tcp上侦听连接并对数据包执行某些操作。

Dim serverstream As NetworkStream
Dim serverstreamw As StreamWriter
Dim serverstreamr As StreamReader
Dim Server As TcpListener
Dim serverclient As New TcpClient
Dim ipendpoint As IPEndPoint = New IPEndPoint(IPAddress.Any, 4001)
Dim mainthread As Threading.Thread

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    mainthread = New Threading.Thread(AddressOf mainserver)
    mainthread.Start()
End Sub

Sub mainserver()
    Try
        Server = New TcpListener(ipendpoint)
        Server.Start()
        serverclient = Server.AcceptTcpClient
        serverstream = serverclient.GetStream
        serverstreamr = New StreamReader(serverstream)
        serverstreamw = New StreamWriter(serverstream)
        While True
            Select Case serverstreamr.ReadLine
                Case "onl" '........
                Case "logoff" '........
                Case "iamhere" '........
                    MessageBox.Show("WORKS!!!")
            End Select
        End While
    Catch

    End Try
End Sub

linux-client:客户端应该与服务器建立连接并向他发送数据包。

echo "iamhere" > /dev/tcp/client.ip/4001

问题是服务器似乎没有打开端口4001 / tcp。客户端没有连接:/

如何解决?

1 个答案:

答案 0 :(得分:1)

连接不起作用的原因是因为你必须在服务器的路由器中forward port 4001。目前它被路由器丢弃,因为端口没有映射到路由器的NAT表中,因此路由器不知道应该向哪个LAN设备发送数据包。

对于仅显示一次的消息框,如果您的Linux代码创建 TCP连接,那么您必须在接收后更改代码以丢弃旧连接消息:

 Try
    Server = New TcpListener(ipendpoint)
    Server.Start()
    While True 'Moved While up here to wait for new connections after every command.
        serverclient = Server.AcceptTcpClient
        serverstream = serverclient.GetStream
        serverstreamr = New StreamReader(serverstream)
        serverstreamw = New StreamWriter(serverstream)
        Select Case serverstreamr.ReadLine
            Case "onl" '........
            Case "logoff" '........
            Case "iamhere" '........
                MessageBox.Show("WORKS!!!")
        End Select
        serverclient.Close() 'Close old connection.
    End While
Catch
End Try

我们这样做的原因是,如果Linux启动新连接而服务器没有,那么服务器仍将等待旧连接上的数据,Linux上不再使用该数据。