VS通过TCPIP与visionpro通讯

效果图

 服务器端

visionpro配置服务器端,配置端口号、需要发送的数据等

 客户端

vs编写代码接收数据

主要是复制的例程,到时候编写的时候可以借鉴。

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

namespace myTCPIPApp
{
    public partial class Form1 : Form
    {
        // Used for thread safe GUI update
        private delegate void UpdateString(string text);

        private TcpClient _client;

        // Thread that is responsible for identifying client connection requests.
        private Thread _connectionThread;
        private long _totalBytes; // record the total number of bytes received

        // Used to log the received data from server
        private StreamWriter _write;

        // When the server is not running from the same machine,
        // change Dns.GetHostName() to the target server name.
        private string hostname = Dns.GetHostName();
        public Form1()
        {
            InitializeComponent();
        }

        private void ConnectButton_Click(object sender, EventArgs e)
        {
            if (ConnectButton.Text == "Connect")
            {
                ConnectToServer();
            }
            else
            {
                StopClient();
            }
        }

        private void ConnectToServer()
        {
            try
            {
                ConnectButton.Text = "Stop";
                //_totalBytes = 0;
                // There is only one connection thread that is used to connect clients.
                _connectionThread = new System.Threading.Thread(new ThreadStart(ReceiveDataFromServer));
                _connectionThread.IsBackground = true;
                _connectionThread.Priority = ThreadPriority.AboveNormal;
                _connectionThread.Name = "Handle Server";
                _connectionThread.Start();
                PortNumberBox.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "QuickBuild Client Sample");
            }
        }

        private void StopClient()
        {
            if (this.InvokeRequired)
            {
                // StopClient can be called after
                // client is closed
                if (ConnectButton.Text != "Connect")
                    this.BeginInvoke(new MethodInvoker(StopClient));
                return;
            }
            Cursor.Current = Cursors.WaitCursor;

            // Change to listen mode
            ConnectButton.Text = "Connect";

            if (_client != null)
            {
                // Close the connection
                _client.Close();

                // Wait for the thread to terminate.
                _connectionThread.Join();
            }

            PortNumberBox.Enabled = true;

            Cursor.Current = Cursors.Default;
        }

        private void ReceiveDataFromServer()
        {
            try
            {
                // Create TcpClient to initiate the connection to the server.
                _client = new TcpClient(hostname,
                  Int32.Parse(PortNumberBox.Value.ToString()));
            }
            catch (SocketException ex)
            {
                //DisplayError(ex.Message);
                return;
            }

            NetworkStream netStream = null;

            try
            {
                netStream = _client.GetStream();
            }
            catch (Exception ex)
            {
                // a bad connection, couldn't get the NetworkStream
                //DisplayError(ex.Message);
                return;
            }
            // Make sure we can read the data from the network stream
            if (netStream.CanRead)
            {
                try
                {
                    // Receive buffer -- should be large enough to reduce overhead.
                    byte[] receiveBuffer = new byte[512];
                    int bytesReceived;                    // Received byte count
                                                          // Read data until server closes the connection.
                    while ((bytesReceived = netStream.Read(receiveBuffer, 0, receiveBuffer.Length)) > 0)
                    {
                        if (_write != null)
                            _write.Write(Encoding.ASCII.GetString(receiveBuffer, 0, bytesReceived));

                        UpdateGUI(Encoding.ASCII.GetString(receiveBuffer, 0, bytesReceived));
                    }
                }
                catch (Exception ex)
                {
                    // Ignore if the error is caused during shutdown
                    // since the stream and client will be closed
                    //if (ConnectButton.Text != "Connect")
                        //DisplayError(ex.Message);
                }
            }

            StopClient();
        }

        private void UpdateGUI(string s)
        {
            if (OutputTextBox.InvokeRequired)
                OutputTextBox.BeginInvoke(new UpdateString(UpdateGUI), new object[] { s });
            else
            {
                if (OutputTextBox.TextLength >= OutputTextBox.MaxLength)
                    OutputTextBox.Text = "";
                OutputTextBox.AppendText(s);
                _totalBytes += s.Length;
                //TotalBytesLabel.Text = _totalBytes.ToString();
            }
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值