TcpClient 错误"不能作任何链接,由于目标机器积极地拒绝它" 的解决

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();         }     } }
相关文章
相关标签/搜索