c#TCP client socket连接方法代码

// RightReciver = System.Text.Encoding.ASCII.GetString(bt);//接收中文出现会出现问号乱码的,改成UTF8就ok了
RightReciver = System.Text.Encoding.UTF8.GetString(bt);

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Drawing;
//namespace MechineOper.CommUnication
namespace AutoPackSystem
{
    class TcpClient1
    {
        // tcp通信对象
        public static Socket tcpClient;
        public static int Lenth = 23;
        public static bool RunFlag = false;
        public static string RightReciver=null;
        public static string LeftReciver=null;
        private int Choice = 1;

        // 通信的远程服务端ip
        private string IP = "127.0.0.1";
        // 通信的远程服务端端口
        private int port = 2000;
        // 心跳字符串
        public string heartString = "< >";
        public static object Obj = new object();
        private bool SendFlag = false;
        //  private bool ReciverFlag = false;
        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ip">服务器IP</param>
        /// <param name="port">服务器开放的通信端口号</param>
        public TcpClient1(string ip, int port,int Ch)
        {
            this.IP = ip;
            this.port = port;
            this.Choice = Ch;
            // tcpClient.Close();
        }
        #endregion
        /// <summary>
        /// 重连服务端
        /// </summary>
        public void Connected()
        {
            try
            {
                tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress iPAddress = IPAddress.Parse(IP);
                EndPoint endPoint = new IPEndPoint(iPAddress, port);
                RunFlag = false;
               // tcpClient.SendTimeout = 1000;
               
                if (!tcpClient.Connected)
                {
                    RunFlag = true;
                    lock (Obj)
                    {
                        tcpClient.Connect(endPoint);
                      //  SendMsg("abc");
                    }
                }
            }
            catch
            {
                tcpClient.Close();
                RunFlag = false;

            }
        }

        public void SendMsg(string msg)
        {
            SendFlag = true;
            while (SendFlag && RunFlag)
            {
                int Lenth = 0;
                try
                {

                    tcpClient.Send(Encoding.ASCII.GetBytes(msg));
                    if (Choice == 2)
                    {
                        byte[] ReciverData = new byte[1024];
                       
                        tcpClient.ReceiveTimeout = 5000;
                        Lenth = tcpClient.Receive(ReciverData);
                        byte[] bt = new byte[Lenth];
                        for(int j = 0; j < Lenth; j++)
                        {
                            bt[j] = ReciverData[j];
                        }
                        // RightReciver = System.Text.Encoding.ASCII.GetString(bt);
                        RightReciver = System.Text.Encoding.UTF8.GetString(bt);
                    }
                    else if (Choice == 1)
                    {
                        byte[] ReciverData = new byte[32];
                        
                        tcpClient.ReceiveTimeout = 5000;
                        Lenth = tcpClient.Receive(ReciverData);
                        byte[] bt = new byte[Lenth];
                        for (int j = 0; j < Lenth; j++)
                        {
                            bt[j] = ReciverData[j];
                        }

                        LeftReciver = System.Text.Encoding.ASCII.GetString(bt);
                       // Console.WriteLine( );
                    }
                    else
                        Lenth = 0;
                    if (Lenth != 0)
                    {
                        SendFlag = false;
                        RunFlag = false;
                        tcpClient.Close();
                    }
                   
                }
                catch
                {
                    // RunFlag = false;
                    SendFlag = false;
                    //tcpClient.Close();
                    tcpClient.Close();
                }
                Thread.Sleep(30);
            }

        }





    }
}
复制代码

 

posted @   txwtech  阅读(1692)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2020-11-29 PLC交通灯编程要求
2019-11-29 cino伟斯 A770键盘界面快速设定记录后缀删除添加换行回车操作方法
2019-11-29 c++深复制与浅复制区别代码示范vs2015-txwtech
点击右上角即可分享
微信分享提示