TCPSend和TCPReceive

//首先创建两个应用程序,一个用于发送消息,一个用于接收消息
//发送消息的程序
     TcpClient tcp = new TcpClient(txtHost.Text, int.Parse(txtPort.Text));
            NetworkStream ns = tcp.GetStream();
            FileStream fs = File.Open("txtTest.txt", FileMode.Open);
            int data = fs.ReadByte();
            while (data != -1)
            {
                ns.WriteByte((byte)data);
                data = fs.ReadByte();
            }
            fs.Close();
            ns.Close();
            tcp.Close();
//创建另一接收程序
 public partial class Form1 : Form
    {
        //定义一个委托,用于更新Form1上控件。
        protected delegate void UpdateDisplayDelegate(string text);
        public Thread thread = null;
        public TcpClient tcpClientReceiver = null;
        TcpListener tcpListener = null;
        public Boolean boolStop = false;
        public Form1()
        {
            InitializeComponent();
            thread = new Thread(new ThreadStart(Listen));
            thread.Start();
        }
        public void Listen()
        {
            string LocalIp = "127.0.0.1";
            if (LocalIp == null)
            {
                return;
            }
            IPAddress localAddr = IPAddress.Parse(LocalIp);
            Int32 port = 8080;
            tcpListener = new TcpListener(localAddr, port);
            tcpClientReceiver = new TcpClient();
            tcpListener.Start();
            while (true)
            {
                if (!tcpListener.Pending())
                {
                    //为了避免每次都被tcpListener.AcceptTcpClient()阻塞线程,添加了此判断,
                    //当没有连接请求时,什么也不做,有了请求再执行到tcpListener.AcceptTcpClient()
                }
                else
                {
                    tcpClientReceiver = tcpListener.AcceptTcpClient();
                    NetworkStream ns = tcpClientReceiver.GetStream();
                    StreamReader sr = new StreamReader(ns);
                    string result = sr.ReadToEnd();
                    Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { result });
                }
                if (boolStop)
                {
                    break;
                }
            }

        }
        public void UpdateDisplay(string text)
        {
            string currentContents = txtDisplay.Text;
            currentContents += text + "\r\n";   //必须用"\r\n"在窗口中才能体现出换行
            txtDisplay.Text = currentContents;
        }
    }

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

双叶红于二月花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值