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

时间:2012-10-11 17:54:59

标签: c# .net tcp

我一直在:

  

“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.
        }
    }
}

1 个答案:

答案 0 :(得分:1)

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

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