Tcp_Client.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.Net.Sockets;
  5. using System;
  6. public class Tcp_Client : MonoBehaviour {
  7. private Tcp_Connect tc;
  8. private string _ip;
  9. private int _port;
  10. // Use this for initialization
  11. void Start()
  12. {
  13. }
  14. // Update is called once per frame
  15. void Update()
  16. {
  17. }
  18. void OnApplicationQuit()
  19. {
  20. Close();
  21. }
  22. //套接字;
  23. private Socket _client;
  24. public void StartUp(string ip, int port)
  25. {
  26. this._ip = ip;
  27. this._port = port;
  28. try
  29. {
  30. _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  31. _client.Connect(ip, port);
  32. tc = new Tcp_Connect(_client, ClientDisabled);
  33. tc.StartUp();
  34. }
  35. catch (Exception e)
  36. {
  37. Debug.Log(e.Message);
  38. Close();
  39. }
  40. }
  41. public void Send(byte[] msg)
  42. {
  43. if (tc != null)
  44. tc.Send(msg);
  45. }
  46. private void ClientDisabled(string token)
  47. {
  48. Close();
  49. StartUp(_ip, _port);
  50. }
  51. /// <summary>
  52. /// 客户端 套接字关闭;
  53. /// </summary>
  54. public void Close()
  55. {
  56. if (tc != null)
  57. {
  58. tc.Close();
  59. }
  60. }
  61. }