我不断得到:
System.dll System.Net.Sockets.SocketException (0x80004005) 中出现“System.Net.Sockets.SocketException”类型的第一次机会异常:无法建立连接,因为目标机器主动拒绝它 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.
}
}
}