加载中...

简单的tcp客户端协议1.0

先添加包

代码部分:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using STTech.BytesIO.Core.Entity;
using STTech.BytesIO.Tcp;

namespace Moutcp
{
    public partial class Form1 : Form
    {
        private TcpClient client ;
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;

            client = new TcpClient() { Port = 60000 };

            propertyGrid.SelectedObject = client;
                
            client.OnDataReceived += Client_OnDataReceived;
            client.OnConnectedSuccessfully += Client_OnConnectedSuccessfully;
            client.OnDisconnected += Client_OnDisconnected;

        }

        private void Client_OnDisconnected(object sender, STTech.BytesIO.Core.Entity.DisconnectedEventArgs e)
        {
            Print($"已断开({e.ReasonCode})");
        }

        private void Client_OnConnectedSuccessfully(object sender, STTech.BytesIO.Core.Entity.ConnectedSuccessfullyEventArgs e)
        {
            Print("连接成功");
        } 

        private void Client_OnDataReceived(object sender, STTech.BytesIO.Core.Entity.DataReceivedEventArgs e)
        {
            Print($"收到数据:{e.Data.EncodeToString("GBK")}");
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            client.Connect();
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            client.Disconnect();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
                client.Send(tbSend.Text.GetBytes("GBK"));
        }
        private void Print(string msg)
        {
            tbRecv.AppendText($"[{DateTime.Now}] {msg}\r\n");
        }
    }
}


实现演示:

posted @ 2025-02-16 14:44  神乐羊  阅读(19)  评论(0)    收藏  举报