using System.Collections; using System.Collections.Generic; using System.Net.Sockets; using System.Net; using UnityEngine; using System; using System.Text; using System.Net.Http; using System.Linq; public class TCP_Client : MonoBehaviour { TcpClient tcpClient; byte[] readbuffer = new byte[1024]; // private string ip = "172.16.1.253"; private string ip = "127.0.0.1"; private int port = 15962; void Start() { StartTcpClient(); } private void OnDestroy() { if (tcpClient != null) { tcpClient.Close(); } } /// /// 启动tcp连接 /// private void StartTcpClient() { tcpClient = new TcpClient(); StartCoroutine(ReConnect()); } [HideInInspector] public bool isconnecting = false; /// /// 检测重连 /// /// IEnumerator ReConnect() { while (true) { if (!tcpClient.Connected && !isconnecting) { Debug.Log("重新连接"); tcpClient = new TcpClient(); isconnecting = true; tcpClient.BeginConnect(IPAddress.Parse(ip), port, Connected, null); } yield return new WaitForSeconds(3); } } private void Connected(IAsyncResult ar) { try { tcpClient.EndConnect(ar); if (tcpClient.Connected) { Debug.Log("连接成功"); tcpClient.GetStream().BeginRead(readbuffer, 0, 1024, Recived, null); //发送appid byte[] tmp = Encoding.UTF8.GetBytes("Id:" + CallForTest.instance.Appid); tcpClient.GetStream().Write(tmp, 0, tmp.Length); Debug.Log("发送appid成功"); } else { Debug.LogError("连接失败"); } } catch (Exception ex) { Debug.LogError(ex.Message); } isconnecting = false; } private void Recived(IAsyncResult ar) { try { int length = tcpClient.GetStream().EndRead(ar); if (length == 0) { Debug.Log("已断开连接"); tcpClient.Close(); return; } else { tcpClient.GetStream().BeginRead(readbuffer, 0, 1024, Recived, null); string str = Encoding.UTF8.GetString(readbuffer, 0, length); Debug.Log(str); CallForTest.instance.infos.Add("TCP参数: "+str); string ticket = str.Split(' ').ToList().Find(a => a.StartsWith("ticket=")); string component_type = str.Split(' ').ToList().Find(a => a.StartsWith("component_type=")); if (ticket != null && component_type!=null) { CallForTest.instance.doChangTask = ticket.Split("ticket=")[1]; CallForTest.instance.doChangeType = component_type.Split("component_type=")[1]; } } } catch (Exception e) { Debug.LogError(e.Message); if (tcpClient.Connected) { tcpClient.GetStream().BeginRead(readbuffer, 0, 1024, Recived, null); } else { Debug.Log("失去连接"); tcpClient.Close(); } return; } } }