1

我有两个应用程序在不同的计算机上运行,​​其中一个是客户端,另一个是服务器,客户端 - > 服务器上的通信完美无缺,尽管它不是相反的方向。

服务器代码:

Imports System.IO
Imports System.Net
Public Class Form1
    Dim listener as Net.Sockets.TcpListener
    Dim listenThread as Threading.Thread

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        listener = New Net.Sockets.TcpListener(Net.IPAddress.Any, 32111)
        listener.Start()
        listenThread = New Threading.Thread(AddressOf DoListen)
        listenThread.IsBackground = True
        listenThread.Start()
End Sub


Private Sub DoListen()
        Dim sr As IO.StreamReader
        Dim sw As IO.StreamWriter
        Do
            Try
                Dim client As Net.Sockets.TcpClient = listener.AcceptTcpClient
                sr = New IO.StreamReader(client.GetStream)
                sw = New IO.StreamWriter(client.GetStream)
                Dim Lines As String() = sr.ReadToEnd.Split(New Char() {","c}) 'get client data

                sr.Close()
                sw.Write("Message123") ' try to send data to client
                sw.Close()

            Catch
            End Try
        Loop
    End Sub
End Class

客户端代码:

Public Class Form1
    Dim Command As String
    Dim thread As Threading.Thread

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        thread = New Threading.Thread(AddressOf MyProcess)
        thread.IsBackground = True
        thread.Start()
    End Sub

Private Sub Send(ByVal Command As String)
        Try
            Dim client As New System.Net.Sockets.TcpClient
            client.Connect(TextBox1.Text, 32111)
            Dim writer As New IO.StreamWriter(client.GetStream)
            writer.Write(Command)
            writer.Flush()
            client.Close()
            MsgBox("Command has been sent successfully")
        Catch ex As Exception
        End Try
    End Sub

Private Sub MyProcess()
        Do
            Dim client As New System.Net.Sockets.TcpClient
            client.Connect("192.168.1.2", 32111)
            Dim reader As New IO.StreamReader(client.GetStream)
            MessageBox.Show(reader.ReadToEnd)
            reader.Close()
            client.Close()
        Loop
    End Sub
End Class

问题是没有任何反应,MessageBox 没有出现在客户端上说“Message123”。

4

1 回答 1

1

每次客户端创建一个新的套接字并连接到它时,它都会在两个应用程序之间打开一个全新的通信通道。在您的示例中,服务器在第一个套接字上返回一条消息,但在客户端上它不会尝试从第一个套接字读取。相反,它会打开第二个套接字并从中读取。您需要更改它,以便从发送请求消息的同一个套接字读取。

如果你仔细想想,你所做的假设不可能是真的。您假设从您的客户端计算机到该端口上的服务器只能有一个有效的套接字。然而显然这不是真的。例如,您可以运行许多单独的 FTP 客户端并连接到同一台服务器。每个应用程序都可以在同一台服务器上为同一端口打开任意数量的套接字,并且它们彼此完全独立。

于 2012-12-02T13:04:38.913 回答