基本信息
源码名称:与S7-1200PLC实现TCP/IP通信 示例
源码大小:0.06M
文件格式:.rar
开发语言:C#
更新时间:2018-02-10
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 5 元 
   源码介绍
与S7-1200PLC实现TCP/IP通信 socket网络编程


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

namespace S7_1200_Control_with_Socket
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            textBoxPort.Text = "2000";
        }

        //给消息文本框加文本的方法
        void ShowMsg(string str)
        {
            textBoxMsg.AppendText(str   "\r\n");
        }

        Socket socketMonitor;
        private void btnStartSever_Click(object sender, EventArgs e)
        {
            try
            {
                //创建IP//Any 字段等效于以点分隔的四部分表示法格式的 0.0.0.0 这个IP地址,实际是一个广播地址。
                //对于SOCKET而言,使用any表示侦听本机的所有IP地址的对应的端口(本机可能有多个IP或只有一个IP)
                IPAddress ip = IPAddress.Any;
                //创建终结点(EndPoint)
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(textBoxPort.Text));
                //建立监视的Socket
                socketMonitor = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                
                socketMonitor.Bind(point);//使得Socket绑定Bind()端口,参数为EndPoint监听
                ShowMsg("监听成功");
                socketMonitor.Listen(0);//参数是监听的最大长度,0是无限
                Thread th = new Thread(Wait);//新建线程,运行socketMonitor(),这里的Listen是自定义的方法
                th.IsBackground = true;//线程为后台属性
                th.Start(socketMonitor);//提供线程要执行的方法的要使用的数据(参数)的对象
            }
            catch
            {   }
        }
        //声明 socketWait 用于等待客户端的连接,创建与之通信用的socketWait并接受信息
        Socket socketWait;
        //将远程连接的客户端的IP地址和Socket存入集合中
        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();

        //被线程执行的函数,用于Accept()新建Socket,把每次的新建Socket,添加RemoteEndPoint到Dic集合,添加到cbo下拉列表框
        //有参数的话,必须是object类型
        private void Wait(object o)
        {
            //throw new NotImplementedException();
            Socket socketMonitor = o as Socket;//as 强转语句,object o参数强转为Socket类型
            while(true)
            {
                try
                {
                    socketWait = socketMonitor.Accept();//等待客户端的连接 并且创建一个负责通信的Socket
                    dicSocket.Add(socketWait.RemoteEndPoint.ToString(), socketWait);//将远程连接的客户端的IP地址和Socket存入集合中
                    comboBoxClient.Items.Add(socketWait.RemoteEndPoint.ToString());//将远程连接的客户端的IP地址和端口号存储下拉框中
                    ShowMsg(socketWait.RemoteEndPoint.ToString()   ":"   "连接成功");//如,192.168.11.78:连接成功
                    Thread th = new Thread(Recive);//开启 一个新线程不停的接受客户端发送过来的消息
                    th.IsBackground = true;
                    th.Start(socketWait);
                }
                catch
                {   }
            }
        }

        //被线程执行的函数,用于服务器端不停的接受客户端发送过来的消息
        private void Recive(object o)
        {
            //throw new NotImplementedException();
            Socket socketWait = o as Socket;
            while(true)
            {
                //客户端连接成功后,服务器应该接受客户端发来的消息
                try
                {
                    byte[] receiveBuffer = new byte[10];
                    //char[] rr = new char[20];
                    //实际接受到的有效字节数
                    int r = socketWait.Receive(receiveBuffer);
                    if (r == 0)
                    {
                        break;
                    }
                    ShowMsg("已接收:"   r.ToString()   "个字节");
                    //string str = Encoding.UTF8.GetString(buffer, 0, r);
                    string str = BitConverter.ToString(receiveBuffer); //将指定的字节子数组的每个元素的数值转换为它的等效十六进制字符串表示形式。
                    ShowMsg(socketWait.RemoteEndPoint   ":"   str);

                    //************未进行高低字节转换
                    //ushort dbw2 = BitConverter.ToUInt16(receiveBuffer, 2); //返回由字节数组中指定位置的两个字节转换来的 16 位无符号整数
                    //ShowMsg(dbw2.ToString());

                    //************进行高低字节转换
                    //*******方法一:
                    //byte[] temp = new byte[2];
                    //Array.Copy(receiveBuffer, 3, temp, 0, 1);
                    //Array.Copy(receiveBuffer, 2, temp, 1, 1);
                    //ushort dbw2ok = BitConverter.ToUInt16(temp, 0);
                    //ShowMsg(dbw2ok.ToString());
                    //*******方法二:
                    byte[] temp = new byte[2];
                    Array.Copy(receiveBuffer,2, temp, 0, 2);
                    Array.Reverse(temp);
                    ushort dbw2ok = BitConverter.ToUInt16(temp, 0);
                    ShowMsg(dbw2ok.ToString());

                }
                catch
                {   }
            }
        }

        private void btnServerSend_Click(object sender, EventArgs e)
        {
            string sendDB = textBoxSend.Text;

            // **************发送DBW型数据*******************
            //ushort dbTemp = Convert.ToUInt16(sendDB);//将数字的指定字符串表示形式转换为等效的 16 位无符号整数
            //byte[] byteTemp = BitConverter.GetBytes(dbTemp);//将指定的数据转换为字节数组
            //进行高低字节转换
            //byte[] sendBuffer = new byte[2];// {0x04, 0xD2};
            //Array.Copy(byteTemp, 1, sendBuffer, 0, 1);
            //Array.Copy(byteTemp, 0, sendBuffer, 1, 1);

            // **************发送REAL型数据************
            double s = Convert.ToDouble(sendDB);//将数字的指定字符串表示形式转换为等效的双精度浮点数
            byte[] byteTemp = BitConverter.GetBytes(s);//double转换后为8个字节
            byte[] sendBuffer = new byte[8];
            //反转整个一维 Array 中元素的顺序,进行高低字节转换
            Array.Reverse(byteTemp);
            socketWait.Send(byteTemp, byteTemp.Length, 0);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            socketWait.Close();
            socketMonitor.Close();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            byte[] sendBuffer = new byte[100];
            socketWait.Send(sendBuffer, sendBuffer.Length, 0);
        }
    }
}