我正在尝试在本地连接的计算机之间建立 TCP 客户端-服务器连接(MacBook-BigSur 是运行服务器,而 Windows 10 笔记本电脑充当客户端)。为此,我使用 Visual Studio Code 运行这两个应用程序,如下所示:
在 macOS 上:
Console.WriteLine("Starting build agent...");
var listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 12345);
Console.WriteLine("Build agent Started ");
listener.Start();
while (true)
{
var fileName = $"s-{DateTime.Now.Ticks}.tar.gz";
using (var client = listener.AcceptTcpClient())
using (var stream = client.GetStream())
using (var output = File.Create(fileName))
{
Console.WriteLine("Client connected. Starting to receive the file...");
// read the file in chunks of 1KB
var buffer = new byte[1024];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
Console.WriteLine("Client connected. File received successfuly.");
Console.WriteLine(Execute($"tar -xvf '{fileName}'"));
}
}
在 Windows 上:
var client = new TcpClient("192.168.0.109", 12345);
Byte[] data = File.ReadAllBytes(@"D:\shared\file.tar.gz");
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
Console.WriteLine("data sent.");
但是,当 Windows 客户端尝试建立连接时,它无法说:
System.Net.Internals.SocketExceptionFactory.ExtendedSocketException: 'No connection could be made because the target machine actively refused it. 192.168.0.109:12345'
请注意,在运行服务器后,我可以通过sudo lsof -i :123456
在终端中使用检查来看到 Visual Studio 正在使用端口 12345 。此外,我的 Mac 设备正在使用端口192.168.0.109
,防火墙已禁用,我可以使用 Windows 命令提示符对其进行 ping 操作。
127.0.0.1
是 localhost,这意味着根据定义,服务器只能在同一主机上访问。
如果您希望服务器侦听所有接口,请不要IPAddress.Any
分别指定IPAddress.IPv6Any
或使用 0.0.0.0。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句