winform下TCP通信的简单应用

先看效果图:

TCP比较繁琐的就是三次握手定理,每次再发送数据前都要先建立连接确认。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;

namespace TCP
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            
            InitializeComponent();
        }
        //启动服务端
        TcpListener listener;
        delegate void SetTextCallBack(string text);
        private void button1_Click(object sender, EventArgs e)
        {
            //try
            //{
                label2.Text = "服务端已开启..";
                button1.Enabled = false;
                listener = new TcpListener(IPAddress.Any, 3000);
                listener.Start();
                Thread th = new Thread(new ThreadStart(ReceiveMsg));
                th.Start();
                th.IsBackground = true;
            //}
            //catch (Exception ex) 
            //{ 
            //    Console.WriteLine(ex.Message); 
            //}
            
        }
        
        public void ReceiveMsg()
        {

            while (true)
            {
                TcpClient client = listener.AcceptTcpClient();
                byte[] buffer = new byte[9899];
                NetworkStream stream = client.GetStream(); 
                int len = stream.Read(buffer, 0, buffer.Length);
                string msg = Encoding.Unicode.GetString(buffer, 0, len);
                SetText(msg);


                stream.Flush();
                stream.Close();
                client.Close();

            }
      

        }
        public void SetText(string text)
        {
            try
            {
                if (this.richTextBox1.InvokeRequired)
                {
                    SetTextCallBack d = new SetTextCallBack(SetText);
                    this.Invoke(d, new object[] { text });
                }
                else
                {

                    this.richTextBox1.Text += DateTime.Now.ToString() + "\n" + text + "\n";
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                //FileStream fs = new FileStream(textBox2.Text,FileMode.OpenOrCreate,FileAccess.Read);
                //byte[] buff=new byte[fs.Length];
                //int rea = fs.Read(buff,0,buff.Length);
                string ip = textBox1.Text;
                string msg = richTextBox2.Text;
                //msg = string.Format("{0}:{1}:{2}:{3}:{4}:{5}",1,DateTime.Now.Ticks,"007","www","32",msg);
                TcpClient client = new TcpClient();
                client.Connect(IPAddress.Parse(ip), 3000);
                NetworkStream stream = client.GetStream();
                byte[] buffer = Encoding.Unicode.GetBytes(msg);
                stream.Write(buffer, 0, buffer.Length);
                //stream.Write(buff,0,rea);
                //label6.Text = "文件发送成功!";
                MessageBox.Show("发送成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show("服务端未开启!");
            }
        }

        private void button2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.button2_Click(sender,e);
            }
        }
        //存放的目录
       // private void button4_Click(object sender, EventArgs e)
       // {
        //    FolderBrowserDialog fbd = new FolderBrowserDialog();
        //    if(fbd.ShowDialog()==DialogResult.OK)
        //    {
         //       textBox3.Text = fbd.SelectedPath;
          //  }
       // }
        //发送的文件
       /// private void button3_Click(object sender, EventArgs e)
       //{
       //     OpenFileDialog ofd = new OpenFileDialog();
       //     if(ofd.ShowDialog()==DialogResult.OK)
       //     {
       //         textBox2.Text = ofd.FileName;
       //     }
       // }
       //文件发送
        //private void button5_Click(object sender, EventArgs e)
        //{         
        //    FileStream fs = new FileStream(textBox2.Text,FileMode.Open,FileAccess.Read);
        //    byte[] buffer = new byte[fs.Length];
        //    int rea=fs.Read(buffer,0,buffer.Length);
        //    TcpClient client = new TcpClient();
        //    string ip = textBox1.Text;
        //    client.Connect(IPAddress.Parse(ip),3000);
        //    NetworkStream ns = client.GetStream();
        //    ns.Write(buffer,0,rea);
        //    MessageBox.Show("文件发送成功!");
        //    fs.Flush();
        //    ns.Flush();
        //    fs.Close();
        //    ns.Close();
        //}    }
}


 

 

 

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#串口介绍以及简单串口通信程序设计实现 源代码和串口程序介绍连接:https://www.cnblogs.com/JiYF/p/6618696.html 本站积分太贵,自己变得。。直接到连接地址下载代码 周末,没事干,写个简单的串口通信工具,也算是本周末曾来过,废话不多,直接到主题 串口介绍   串行接口简称串口,也称串行通信接口或串行通讯接口(通常指COM接口),是采用串行通信方式的扩展接口。(至于再详细,自己百度) 串口应用:   工业领域使用较多,比如:数据采集,设备控制等等,好多都是用串口通信来实现!你要是细心的话,你会发现,目前家用国网智能电能表就具备RS485通信总线(串行总线的一种)与RS232可以相互转化(当然一般,非专业的谁也不会闲的蛋疼,趴电表上瞎看,最多也就看看走了多少度电) RS232 DB9介绍: 1.示意图 2.针脚介绍: 载波检测(DCD) 接受数据(RXD) 发出数据(TXD) 数据终端准备好(DTR) 信号地线(SG) 数据准备好(DSR) 请求发送(RTS) 清除发送(CTS) 振铃指示(RI) 3.实物图: 以下是我购买XX公司的一个usb转串口线:这个头就是一个公头,另一端是一个usb口 笨小孩串口工具运行图: 1.开启程序 2.发送一行字符串HelloBenXH,直接将针脚的发送和接收链接起来就可以测试了(针脚2 接受数据(RXD) 和3 发出数据(TXD))直接链接, C#代码实现:采用SerialPort 1.实例化一个SerialPort [csharp] view plain copy 在CODE上查看代码片派生到我的代码片 private SerialPort ComDevice = new SerialPort(); 2.初始化参数绑定接收数据事件 [csharp] view plain copy 在CODE上查看代码片派生到我的代码片 public void init() { btnSend.Enabled = false; cbbComList.Items.AddRange(SerialPort.GetPortNames()); if (cbbComList.Items.Count > 0) { cbbComList.SelectedIndex = 0; } cbbBaudRate.SelectedIndex = 5; cbbDataBits.SelectedIndex = 0; cbbParity.SelectedIndex = 0; cbbStopBits.SelectedIndex = 0; pictureBox1.BackgroundImage = Properties.Resources.red; ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);//绑定事件 }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值