1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.Net.Sockets;
    5. using UnityEngine;
    6. using UnityEngine.UI;
    7. public class Echo : MonoBehaviour
    8. {
    9. //定义套接字
    10. Socket socket;
    11. //UGUI
    12. public InputField inputField;
    13. public Text text;
    14. //接受缓冲区
    15. byte[] readBuff = new byte[1024];
    16. string recvStr = "";
    17. /// <summary>
    18. /// 点击连接按钮
    19. /// </summary>
    20. public void Connection()
    21. {
    22. //Socket
    23. socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    24. //Connect
    25. socket.BeginConnect("127.0.0.1", 8888, ConnectCallback, socket);
    26. }
    27. /// <summary>
    28. /// Connect回调
    29. /// </summary>
    30. /// <param name="ar"></param>
    31. public void ConnectCallback(IAsyncResult ar)
    32. {
    33. try
    34. {
    35. Socket socket = (Socket)ar.AsyncState;
    36. socket.EndConnect(ar);
    37. Debug.Log("Socket Connect Succ");
    38. socket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, socket);
    39. }
    40. catch (SocketException ex)
    41. {
    42. Debug.Log("Socket Connect fail" + ex.ToString());
    43. }
    44. }
    45. /// <summary>
    46. /// Receive回调
    47. /// </summary>
    48. /// <param name="ar"></param>
    49. public void ReceiveCallback(IAsyncResult ar)
    50. {
    51. try
    52. {
    53. Socket socket = (Socket)ar.AsyncState;
    54. int count = socket.EndReceive(ar);
    55. recvStr = System.Text.Encoding.Default.GetString(readBuff, 0, count);
    56. socket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, socket);
    57. }
    58. catch (Exception ex)
    59. {
    60. Debug.Log("Socket Receive fail" + ex.ToString());
    61. }
    62. }
    63. /// <summary>
    64. /// 点击发送按钮
    65. /// </summary>
    66. public void Send()
    67. {
    68. //Send
    69. string sendStr = inputField.text;
    70. byte[] sendBytes = System.Text.Encoding.Default.GetBytes(sendStr);
    71. socket.BeginSend(sendBytes, 0, sendBytes.Length, 0, SendCallback, socket);
    72. //后面就不需要Receive了
    73. }
    74. //Send回调
    75. public void SendCallback(IAsyncResult ar)
    76. {
    77. try
    78. {
    79. Socket socket = (Socket)ar.AsyncState;
    80. int count = socket.EndSend(ar);
    81. Debug.Log("Socket Send succ" + count);
    82. }
    83. catch (SocketException ex)
    84. {
    85. Debug.Log("Socket Send fail" + ex.ToString());
    86. }
    87. }
    88. public void Update()
    89. {
    90. text.text = recvStr;
    91. }
    92. }