gpt4 book ai didi

c# - 无法通过 TCP 发送或接收消息

转载 作者:可可西里 更新时间:2023-11-01 02:52:40 24 4
gpt4 key购买 nike

我不断得到:

A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it 911.00.00.666:13000

即使在我允许该应用程序通过 Windows 防火墙之后。我还尝试了端口 80、8080 和 13000。

为什么总是这样?我该如何解决?

我正在学习本教程:http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient(v=vs.110).aspx#Y2523

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
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;

namespace TCPTestClient
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

String msgToSend = "Hello, dude.";

private void button_Click_1(object sender, RoutedEventArgs e)
{
try
{
Int32 port = 13000;

TcpClient client = new TcpClient("localhost", port);

Byte[] data = System.Text.Encoding.ASCII.GetBytes(msgToSend);

NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);

Console.WriteLine("Send: {0}", msgToSend);

data = new Byte[256];

String response = String.Empty;

Int32 bytes = stream.Read(data, 0, data.Length);
response = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", response);

title.Text = response;

stream.Close();
client.Close();
}
catch (ArgumentNullException ex)
{
Console.WriteLine(ex);
}
catch (SocketException s)
{
Console.WriteLine(s);
}

Console.WriteLine("Done");
// All done.
}
}
}

最佳答案

链接的文档假设有一个服务器正在运行并接受相关端口上的连接。您的代码只是一个客户端。它需要一个服务器才能连接。

参见 Socket有关如何运行服务器的信息的类。

关于c# - 无法通过 TCP 发送或接收消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12845657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com