我有两个应用程序在不同的计算机上运行,其中一个是客户端,另一个是服务器,客户端上的通信 - >服务器工作得很好,虽然它没有相反的方向。
服务器代码:
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”。
答案 0 :(得分:1)
每次客户端创建一个新套接字并连接到它时,它就会在两个应用程序之间打开一个全新的通信通道。在您的示例中,服务器在第一个套接字上返回一条消息,但在客户端上它不会尝试从第一个套接字读取。相反,它打开第二个套接字并从中读取。您需要更改它,以便从您发送请求消息的同一个套接字读取。
如果你考虑一下,你正在做出一个不可能是真实的假设。您假设从客户端计算机到该端口上的服务器只能有一个有效的套接字。但显然这不是真的。例如,您可以运行许多单独的FTP客户端和同一服务器。每个应用程序都可以在同一台服务器上打开尽可能多的套接字,并且它们完全相互独立。