C# TCP 通讯

//接收

using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
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 TcpReceiver
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Thread th = new Thread(new ThreadStart(RecvData));
            th.Start();
        }


        private void RecvData()
        {
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");
            int port = 10001;


            TcpListener listener = new TcpListener(localAddr, port);
            listener.Start();
            TcpClient client = listener.AcceptTcpClient();
            NetworkStream ns = client.GetStream();

            StreamReader sr = new StreamReader(ns);
            string result = sr.ReadToEnd();
            Invoke(new UpdateDisplayDelegate(UpdateDisplay), new Object[] { result });
            client.Close();
            listener.Stop();
        }


        delegate void UpdateDisplayDelegate(string text);

        void UpdateDisplay(string text)
        {
            txtRecv.Text = text;
        }
    }

}


//发送

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.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace TcpExam
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void btnSend_Click(object sender, EventArgs e)
        {
            TcpClient client = new TcpClient(txtHost.Text, int.Parse(txtPort.Text));
            NetworkStream ns = client.GetStream();
            FileStream fs = File.Open("Form1.cs",FileMode.Open);

            int t = fs.ReadByte();
            while (t != -1)
            {
                ns.WriteByte((byte)t);
                t = fs.ReadByte();
            }
            fs.Close();
            ns.Close();
            client.Close();
        }
    }
}

<think>好的,用户想了解C#TCP通信的实现方法,特别是示例。首先我需要回忆一下C#TCP通信的基本知识。C#主要通过System.Net.Sockets命名空间下的TcpListener和TcpClient类来实现TCP通信。用户提到的示例可能需要分为服务器端和客户端的代码。 首先,我应该先确定用户的具体需求。用户提到了与西门子PLC通信的引用,但问题更偏向于一般的C# TCP通信实现。可能需要先提供一个基础的示例,然后说明如何适配到PLC通信的特殊需求,比如协议格式。 接下来,结构应该清晰。分步骤讲解服务器和客户端的实现。服务器端需要创建TcpListener,开始监听,接受客户端连接,然后处理数据流。客户端则使用TcpClient连接到服务器,发送和接收数据。 要注意代码的准确性和可运行性。比如,在服务器端,使用Start()方法启动监听,AcceptTcpClient()会阻塞直到有连接。读写数据使用NetworkStream,记得处理编码,比如使用Encoding.ASCII.GetBytes和GetString进行转换。 同时,异常处理也很重要,比如使用try-catch块来捕获可能的Socket异常,确保资源被正确释放,比如使用using语句来关闭连接和流。 用户可能还需要知道如何处理多客户端的情况,这里可能提到使用异步方法或者多线程,但基础示例可能先展示单线程同步处理,之后再扩展到异步。 然后,根据用户提供的引用[^1],可能需要补充与西门子PLC通信时的注意事项,比如特定的报文格式、握手协议,或者保持连接的方法。比如,西门子PLC可能使用基于RFC 1006的协议,需要发送特定的初始化消息,或者处理字节顺序的问题。 最后,生成相关问题的时候,应该围绕TCP通信的常见问题,比如如何处理粘包、多线程处理、异常处理、提高通信效率的方法,以及如何调试通信问题等。这样用户可以根据示例进一步深入学习。</think>### C# TCP通信实现方法分步说明 #### 1. 服务器端实现 ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; class TcpServer { public static void Main() { TcpListener server = new TcpListener(IPAddress.Any, 8080); server.Start(); Console.WriteLine("服务器已启动,等待连接..."); TcpClient client = server.AcceptTcpClient(); Console.WriteLine($"客户端已连接: {client.Client.RemoteEndPoint}"); using (NetworkStream stream = client.GetStream()) { byte[] buffer = new byte[1024]; int bytesRead = stream.Read(buffer, 0, buffer.Length); string receivedData = Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine($"收到数据: {receivedData}"); string response = "服务器已接收"; byte[] responseData = Encoding.ASCII.GetBytes(response); stream.Write(responseData, 0, responseData.Length); } server.Stop(); } } ``` #### 2. 客户端实现 ```csharp using System; using System.Net.Sockets; using System.Text; class TcpClientExample { public static void Main() { TcpClient client = new TcpClient("127.0.0.1", 8080); Console.WriteLine("已连接到服务器"); using (NetworkStream stream = client.GetStream()) { string message = "Hello Server!"; byte[] data = Encoding.ASCII.GetBytes(message); stream.Write(data, 0, data.Length); Console.WriteLine($"已发送: {message}"); byte[] buffer = new byte[1024]; int bytesRead = stream.Read(buffer, 0, buffer.Length); string response = Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine($"收到响应: {response}"); } client.Close(); } } ``` #### 3. 关键要素说明 1. **端口绑定**:服务器端通过`IPAddress.Any`绑定所有可用IP地址 2. **数据编码**:使用ASCII编码进行字节转换,可根据需要改为UTF-8 3. **流操作**:`NetworkStream`提供同步/异步读写方法 4. **异常处理**:建议添加`try-catch`块处理`SocketException` #### 4. 西门子PLC通信适配 在工业控制场景中,需注意: - 使用ISO-on-TCP协议(RFC 1006) - 遵循西门子S7通信协议格式 - 添加握手协议和心跳机制 - 处理大端序数据格式[^1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值