润宇软件
首 页 企业简介 项目案例 软件定制 行业软件 解决方案 企业资讯 服务专区 客服中心
业务介绍:西安软件公司、软件开发、软件定制、软件外包
软件 方案 文章
  润宇软件 >> 新闻资讯  >> 解决方案

软件公司中C#中的串口,网口和PLC通讯

发布时间:2022/8/18  浏览次数:次  字体【    】
串口:串口是一个泛称,UART、TTL、RS232、RS485都遵循类似的通信时序协议,因此都被通称为串口 
RS232:是电子工业协会(Electronic Industries Association,EIA) 制定的异步传输标准接口,同时对应着电平标准和通信协议(时序),其电平标准:+3V~+15V对应0,-3V~-15V对应1。rs232 的逻辑电平和TTL 不一样但是协议一样 
RS485:RS485是一种串口接口标准,为了长距离传输采用差分方式传输,传输的是差分信号,抗干扰能力比RS232强很多。两线压差为-(2~6)V表示0,两线压差为+(2~6)V表示1 
TCP/IP 是互联网相关的各类协议族的总称,比如:TCP,UDP,IP,FTP,HTTP,ICMP,SMTP 等都属于 TCP/IP 族内的协议。像这样把与互联网相关联的协议集合起来总称为 TCP/IP。也有说法认为,TCP/IP 是指 TCP 和 IP 这两种协议。还有一种说法认为,TCP/IP 是在 IP 协议的通信过程中,使用到的协议族的统称。

c# tcp/ip通信

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace csharpService
{
    public partial class Service : Form
    {
        public Service()
        {
            InitializeComponent();
            ///多线程编程中,如果子线程需要使用主线程中创建的对象和控件,最好在主线程中体现进行检查取消
            ///
            CheckForIllegalCrossThreadCalls = false;
            /// 获取本地IP
            textBox_current_address.Text = IPAddress.Any.ToString();
        }
        /// 创建一个字典,用来存储记录服务器与客户端之间的连接(线程问题)
        ///
        private Dictionary<string, Socket> clientList = new Dictionary<string, Socket>();
        /// 创建连接
        private void button_connect_Click(object sender, EventArgs e)
        {
            Thread myServer = new Thread(MySocket);
            //设置这个线程是后台线程
            myServer.IsBackground = true;
            myServer.Start();
        }
        //①:创建一个用于监听连接的Socket对象;
        //②:用指定的端口号和服务器的Ip建立一个EndPoint对象;
        //③:用Socket对象的Bind()方法绑定EndPoint;
        //④:用Socket对象的Listen()方法开始监听;
        //⑤:接收到客户端的连接,用Socket对象的Accept()方法创建一个新的用于和客户端进行通信的Socket对象;
        //⑥:通信结束后一定记得关闭Socket。
        /// 创建连接的方法
        private void MySocket()
        {
            //1.创建一个用于监听连接的Socket对象;
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            //2.用指定的端口号和服务器的Ip建立一个EndPoint对象;
            IPAddress iP = IPAddress.Parse(textBox_current_address.Text);
            IPEndPoint endPoint = new IPEndPoint(iP, int.Parse(textBox_port.Text));
            //3.用Socket对象的Bind()方法绑定EndPoint;
            server.Bind(endPoint);
            //4.用Socket对象的Listen()方法开始监听;
            //同一时刻内允许同时加入链接的最大数量
            server.Listen(20);
            listBox_log.Items.Add("服务器已经成功开启!");
            //5.接收到客户端的连接,用Socket对象的Accept()方法创建一个新的用于和客户端进行通信的Socket对象;
            while (true)
            {
                //接受接入的一个客户端
                Socket connectClient = server.Accept();
                if (connectClient != null)
                {
                    string infor = connectClient.RemoteEndPoint.ToString();
                    clientList.Add(infor, connectClient);
                    listBox_log.Items.Add(infor + "加入服务器!");
                    ///服务器将消息发送至客服端
                    string msg = infor + "已成功进入到聊天室!";
                    SendMsg(msg);
                    //每有一个客户端接入时,需要有一个线程进行服务
                    Thread threadClient = new Thread(ReciveMsg);//带参的方法可以把传递的参数放到start中
                    threadClient.IsBackground = true;
                    //创建的新的对应的Socket和客户端Socket进行通信
                    threadClient.Start(connectClient);
                }
            }
        }
        /// 服务器接收到客户端发送的消息
        private void ReciveMsg(object o)
        {
            //Socket connectClient = (Socket)o; //与下面效果一样
            Socket connectClient = o as Socket;//connectClient负责客户端的通信
            IPEndPoint endPoint = null;
            while (true)
            {
                try
                {
                    ///定义服务器接收的字节大小
                    byte[] arrMsg = new byte[1024 * 1024];
                    ///接收到的信息大小(所占字节数)
                    int length = connectClient.Receive(arrMsg);

                    if (length > 0)
                    {
                        string recMsg = Encoding.UTF8.GetString(arrMsg, 0, length);
                        //获取客户端的端口号
                        endPoint = connectClient.RemoteEndPoint as IPEndPoint;
                        //服务器显示客户端的端口号和消息
                        listBox_log.Items.Add(DateTime.Now + "[" + endPoint.Port.ToString() + "]:" + recMsg);
                        //服务器(connectClient)发送接收到的客户端信息给客户端
                        SendMsg("[" + endPoint.Port.ToString() + "]:" + recMsg);
                    }
                }
                catch (Exception)
                {
                    ///移除添加在字典中的服务器和客户端之间的线程
                    clientList.Remove(endPoint.ToString());
                    connectClient.Dispose();


                }
            }
        }
        /// 服务器发送消息,客户端接收
        private void SendMsg(string str)
        {
            ///遍历出字典中的所有线程
            foreach (var item in clientList)
            {
                byte[] arrMsg = Encoding.UTF8.GetBytes(str);
                ///获取键值(服务器),发送消息
                item.Value.Send(arrMsg);
            }
        }
    }
}
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace csharp_Client
{
    public partial class Client : Form
    {
        public Client()
        {
            InitializeComponent();
            ///多线程编程中,如果子线程需要使用主线程中创建的对象和控件,最好在主线程中体现进行检查取消
            CheckForIllegalCrossThreadCalls = false;
        }
        /// 创建客户端
        private Socket client;
        private void button_connect_Click(object sender, EventArgs e)
        {
            ///创建客户端
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            ///IP地址
            IPAddress ip = IPAddress.Parse(textBox_address.Text);
            ///端口号
            IPEndPoint endPoint = new IPEndPoint(ip, int.Parse(textBox_port.Text));
            ///建立与服务器的远程连接
            try
            {
                client.Connect(endPoint);
            }
            catch(Exception)
            {
                MessageBox.Show("地址或端口错误!!!!");
                return;
            }
            ///线程问题
            Thread thread = new Thread(ReciveMsg);
            thread.IsBackground = true;
            thread.Start(client);
        }
        /// 客户端接收到服务器发送的消息
        private void ReciveMsg(object o)
        {
            Socket client = o as Socket;
            while (true)
            {
                try
                {
                    ///定义客户端接收到的信息大小
                    byte[] arrList = new byte[1024 * 1024];
                    ///接收到的信息大小(所占字节数)
                    int length = client.Receive(arrList);
                    string msg = DateTime.Now + Encoding.UTF8.GetString(arrList, 0, length);
                    listBox_log.Items.Add(msg);
                }
                catch (Exception)
                {
                    ///关闭客户端
                    client.Close();
                }
            }
        }
        /// 客户端发送消息给服务端
        private void button_send_Click(object sender, EventArgs e)
        {
            if (textBox_message.Text != "")
            {
                SendMsg(textBox_message.Text);
            }
        }
        /// 客户端发送消息,服务端接收
        private void SendMsg(string str)
        {
            byte[] arrMsg = Encoding.UTF8.GetBytes(str);
            client.Send(arrMsg);
        }

        private void Client_FormClosed(object sender, FormClosedEventArgs e)
        {
            if(client!=null) client.Close();
        }
    }
}
  关闭本页
西部IT网合作伙伴 合作伙伴
陕西省 | 榆林 | 延安 | 铜川 | 渭南 | 商洛 | 宝鸡 | 汉中 | 安康 | 咸阳
网站首页 | 关于我们 | 售后服务 | 项目合同 | 查看留言 | 在线留言 | 客服中心
© 版权所有:西安润宇软件科技有限公司 
公司地址:西安市丝路国际创意梦工厂4号楼 联系电话:029-87878512 手机:13468700578 联系人:李先生
Copyright ® 2009-2015 RunYusoft.com Inc. All Rights Reserved 
技术支持:西安润宇软件科技有限公司  陕ICP备11000720号