【发布时间】:2012-10-12 02:04:40
【问题描述】:
我不断得到:
“System.Net.Sockets.SocketException”类型的第一次机会异常 发生在 System.dll System.Net.Sockets.SocketException (0x80004005): 无法建立连接,因为目标机器 主动拒绝 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.
}
}
}
【问题讨论】:
-
这个
911.00.00.666是什么IP? -
确保13000端口是开放的,可以接受消息,否则会失败。此外,您也可以使用实际的本地地址(作为字符串)而不是“localhost”。
-
@L.B 我改变了它,因为我很偏执。 :-)
-
@ChristopherBales 谢谢。我不确定如何检查,但我现在正在查找。
-
@ChristopherBales 我最初确实尝试了我的实际本地地址,但这导致了同样的异常被抛出。