【发布时间】:2021-03-31 01:55:06
【问题描述】:
我正在为一个项目开发一个 GUI,该项目返回来自 python 客户端的输出。我想测试 C# 服务器和基本 Python 客户端之间的基本连接,但由于某种原因,每当我运行 Python 时,它都会显示 “ConnectionRefusedError: [WinError 10061] 无法建立连接,因为目标机器主动拒绝了它”。我从过去的经验中知道,这可能与服务器无法正确打开或以某种方式无法连接有关。但是,我无法解决问题所在。我对 C# 很陌生,所以我从互联网上获取了一个服务器代码,只是为了进行一些测试。 我有一个带有简单按钮的主窗口,当我单击它时,我希望它打开套接字连接。 MainWindow.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ServerOn;
namespace GUI243
{
public partial class MainWindow : Window
{
public MainWindow()
{
Server server = new Server();
InitializeComponent();
}
private void Test_Click(object sender, RoutedEventArgs e)
{
Server.ExecuteServer();
}
}
}
C# 服务器:
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
namespace ServerOn
{
class Server
{
public static void ExecuteServer()
{
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 5400);
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(5);
while (true)
{
MessageBox.Show("Waiting connection ... ");
Socket clientSocket = listener.Accept();
// Data buffer
byte[] bytes = new Byte[1024];
string data = null;
bool flag = false;
while (!flag)
{
int numByte = clientSocket.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,
0, numByte);
MessageBox.Show("Text received -> {0} ", data);
if (data.Equals("end"))
{
flag = true;
}
}
// byte[] message = Encoding.ASCII.GetBytes("Test Server");
// clientSocket.Send(message);
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
}
}
Python 客户端:
import socket
def client_program():
host = socket.gethostname() # as both code is running on same pc
port = 5400 # socket server port number
client_socket = socket.socket() # instantiate
client_socket.connect((host, port)) # connect to the server
message = input(" -> ") # take input
while message.lower().strip() != 'end':
client_socket.send(message.encode()) # send message
message = input(" -> ") # again take input
client_socket.close() # close the connection
if __name__ == '__main__':
client_program()
【问题讨论】:
-
您正在侦听一个特定 IP,它可能是 IPv6,也许
::1。考虑监听 IPAddress.Any。 -
索引零 (ipHost.AddressList[0];) 通常是 IPV6,索引一是 IPV4。此错误还有很多其他原因。最简单的方法是尝试更改索引。