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); } } } }
欢迎讨论,相互学习。
cdtxw@foxmail.com