TcpClient 错误"不能做任何连接,因为目标机器积极地拒绝它" 的解决

//以下是tcpclient服务器端的监听程序,假设服务器端和客户端在同一台机器上,
//为了使客户端可以使用localhost/127.0.0.1/192.168.1.2等多种情况,
//应该使用IPAddress.Any,而不是指定一个ip,以下是msdn的说明
//msdn
//此构造函数允许指定本地 IP 地址和用于侦听传入的连接尝试的端口号。在调用该构造函数之前,必须首先使用所需的本//地地址创建 IPAddress。将此 IPAddress 作为 localaddr 参数传递给构造函数。如果您不介意分配哪个本地地址,//请将 localaddr 参数指定为 IPAddress.Any,这样基础服务提供程序将分配最适合的网络地址。如果您有多个网络接//口,这将有助于简化您的应用程序。如果您不介意使用哪个本地端口,可以指定 0 作为端口号。在这种情况下,服务提供//程序将分配一个介于 1024 和 5000 之间的可用端口号。如果使用这种方法,则可以使用 LocalEndpoint 属性发现所//分配的本地网络地址和端口号。

//以下是服务器端的程序
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace TcpReceive
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            Thread thread = new Thread(new ThreadStart(MyListen));
            thread.Start();
        }

        public void MyListen()
        {
            IPAddress localAddr = IPAddress.Parse("192.168.1.2");
            Int32 port = 2112;
            TcpListener tcpListen = new TcpListener(IPAddress.Any,port);
            tcpListen.Start();

            while (true)
            {
                TcpClient tcpClient = tcpListen.AcceptTcpClient();

                NetworkStream ns = tcpClient.GetStream();
                StreamReader sr = new StreamReader(ns);
                string res = sr.ReadToEnd();

                Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { res });
            }

            //tcpClient.Close();
            //tcpListen.Stop();
 
        }

        public void UpdateDisplay(string text)
        {
            this.textBox1.Text += text;
        }

        protected delegate void UpdateDisplayDelegate(string Text);

    }
}

//以下是客户端程序
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Net.Sockets;

namespace TcpSend
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            TcpClient tcpClient = new TcpClient(this.textBox1.Text,int.Parse(this.textBox2.Text));
            NetworkStream ns = tcpClient.GetStream();
            FileStream fs = File.Open("d:\\123.txt",FileMode.Open);

            int data = fs.ReadByte();
            while (data != -1)
            {
                ns.WriteByte((byte)data);
                data=fs.ReadByte();
            }
            fs.Close();
            ns.Close();
            tcpClient.Close();

        }
    }
}

原文地址:https://www.cnblogs.com/baishahe/p/1028092.html