ClientSocket.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. class ClientSocket
  14. {
  15. private byte[] buffers;
  16. private Socket clientSocket;
  17. private int port = 8081;
  18. private string host = "127.0.0.1";
  19. //private string host = "39.107.246.58";
  20. public ClientSocket()
  21. {
  22. this.buffers = new byte[1100];
  23. }
  24. private Socket clientConnect(int port, string host)
  25. {
  26. IPAddress ip = IPAddress.Parse(host);
  27. IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
  28. Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
  29. c.NoDelay = true;
  30. Console.WriteLine("Conneting...");
  31. try
  32. {
  33. c.Connect(ipe);//连接到服务器 ;
  34. return c;
  35. }
  36. catch (Exception e)
  37. {
  38. throw e;
  39. //Thread.Sleep(1000);
  40. //clientConnect(port, host);
  41. //return c;
  42. }
  43. return null;
  44. }
  45. public void Receive()
  46. {
  47. try
  48. {
  49. clientSocket = clientConnect(port, host);
  50. while (true)//循环接收发送信息
  51. {
  52. // Thread.Sleep(16);
  53. int length = 1;
  54. int packageNumber = 0;//包序
  55. int row = 0;
  56. while (length > 0)
  57. {
  58. clientSocket.Receive(buffers);
  59. }
  60. }
  61. }
  62. catch (Exception e)
  63. {
  64. }
  65. finally
  66. {
  67. clientSocket.Close();
  68. }
  69. }
  70. public string byteToHexStr(byte[] bytes)
  71. {
  72. string returnStr = "";
  73. if (bytes != null)
  74. {
  75. for (int i = 0; i < bytes.Length; i++)
  76. {
  77. returnStr += bytes[i].ToString("X2");
  78. }
  79. }
  80. return returnStr;
  81. }
  82. }