当前位置:   article > 正文

【Unity Socket】Unity Socket TCP网络编程基础_unity网络编程

unity网络编程

Socket通讯基本流程图

1、服务端

1.1 创建服务器端Socket对象,负责监听客户端连接

  1. // 1.创建服务器端Socket对象,负责监听客户端连接
  2. socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

1.2 绑定IP与端口

  1. IPAddress ip = IPAddress.Parse(_ip);
  2. IPEndPoint point = new IPEndPoint(ip, _port); //创建对象端口
  3. // 2.绑定IP与端口
  4. socketWatch.Bind(point);

 1.3 设置监听,设置最大监听数

  1. // 3.设置监听,设置最大监听数
  2. socketWatch.Listen(10);

1.4 等待接收客户端连接(返回用于和客户端通讯的Socket)

  1. // 4.等待接收客户端连接(返回用于和客户端通讯的Socket)
  2. while(true)
  3. {
  4. socketSend = socketWatch.Accept(); //等待接收客户端连接
  5. }

 1.5 接收消息

  1. // 5.接收消息
  2. int len = socketSend.Receive(buffer); //实际接收到的有效字节数

1.6 发送消息

  1. // 6.发送消息
  2. socketSend.Send(sendByte);

 1.7 关闭Socket

  1. // 7.关闭Socket
  2. socketWatch.Shutdown(SocketShutdown.Both); //禁用Socket的发送和接收功能
  3. socketWatch.Close(); //关闭Socket连接并释放所有相关资源
  4. socketSend.Shutdown(SocketShutdown.Both); //禁用Socket的发送和接收功能
  5. socketSend.Close(); //关闭Socket连接并释放所有相关资源

2、客户端

2.1 创建一个Socket对象(和服务端进行通讯)

  1. // 1.创建一个Socket对象(和服务端进行通讯)
  2. socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

2.2 连接服务器

  1. IPAddress ip = IPAddress.Parse(_ip);
  2. IPEndPoint point = new IPEndPoint(ip, _port);
  3. // 2.连接服务器
  4. socketSend.Connect(point);

 2.3 接受消息

  1. // 3.接受消息
  2. int len = socketSend.Receive(buffer);

 2.4 发送消息

  1. // 4.发送消息
  2. socketSend.Send(buffer);

2.5 关闭Socket

  1. // 5.关闭Socket
  2. socketSend.Shutdown(SocketShutdown.Both); //禁用Socket的发送和接收功能
  3. socketSend.Close(); //关闭Socket连接并释放所有相关资源

 

 3、简单实现完整代码

3.1 服务端

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Net;
  5. using System.Net.Sockets; //调用socket
  6. using System.Text;
  7. using System.Threading; //调用线程
  8. using UnityEngine;
  9. using System.IO;
  10. public class TCPServer : MonoBehaviour
  11. {
  12. //定义变量(与GUI一致)
  13. private string info = "NULL"; //状态信息
  14. private string recMes = "NULL"; //接收到的信息
  15. private int recTimes = 0; //接收到的信息次数
  16. private string inputIp = "127.0.0.1"; //ip地址(本地)
  17. private string inputPort = "8080"; //端口值
  18. private string inputMessage = "NULL"; //用以发送的信息
  19. private Socket socketWatch; //用以监听的套接字
  20. private Socket socketSend; //用以和客户端通信的套接字
  21. private bool isSendData = false; //是否点击发送数据按钮
  22. private bool clickConnectBtn = false; //是否点击监听按钮
  23. // Start is called before the first frame update
  24. void Start()
  25. {
  26. }
  27. // Update is called once per frame
  28. void Update()
  29. {
  30. }
  31. //建立tcp通信链接
  32. private void ClickConnect()
  33. {
  34. try
  35. {
  36. int _port = Convert.ToInt32(inputPort); //获取端口号(32位,4个字节)
  37. string _ip = inputIp; //获取ip地址
  38. Debug.Log(" ip 地址是 :" + _ip);
  39. Debug.Log(" 端口号是 :" + _port);
  40. clickConnectBtn = true; //点击了监听按钮,更改状态
  41. info = "ip地址是 : " + _ip + "端口号是 : " + _port;
  42. // 1.创建服务器端Socket对象,负责监听客户端连接
  43. socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  44. IPAddress ip = IPAddress.Parse(_ip);
  45. IPEndPoint point = new IPEndPoint(ip, _port); //创建对象端口
  46. // 2.绑定IP与端口
  47. socketWatch.Bind(point); //绑定端口号
  48. Debug.Log("监听成功!");
  49. info = "监听成功";
  50. // 3.设置监听,设置最大监听数
  51. socketWatch.Listen(10); //设置监听,最大同时连接10台
  52. //创建监听线程
  53. Thread thread = new Thread(Listen);
  54. thread.IsBackground = true;
  55. thread.Start(socketWatch);
  56. }
  57. catch { }
  58. }
  59. /// <summary>
  60. /// 等待客户端的连接 并且创建与之通信的Socket
  61. /// </summary>
  62. void Listen(object o)
  63. {
  64. try
  65. {
  66. Socket socketWatch = o as Socket;
  67. while (true)
  68. {
  69. // 4.等待接收客户端连接(返回用于和客户端通讯的Socket)
  70. socketSend = socketWatch.Accept(); //等待接收客户端连接
  71. Debug.Log(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功!");
  72. info = socketSend.RemoteEndPoint.ToString() + " 连接成功!";
  73. Thread r_thread = new Thread(Received); //开启一个新线程,执行接收消息方法
  74. r_thread.IsBackground = true;
  75. r_thread.Start(socketSend);
  76. Thread s_thread = new Thread(SendMessage); //开启一个新线程,执行发送消息方法
  77. s_thread.IsBackground = true;
  78. s_thread.Start(socketSend);
  79. }
  80. }
  81. catch { }
  82. }
  83. // 服务器端不停的接收客户端发来的消息
  84. void Received(object o)
  85. {
  86. try
  87. {
  88. Socket socketSend = o as Socket;
  89. while (true)
  90. {
  91. byte[] buffer = new byte[1024 * 6]; //客户端连接服务器成功后,服务器接收客户端发送的消息
  92. // 5.接收消息
  93. int len = socketSend.Receive(buffer); //实际接收到的有效字节数
  94. if (len == 0)
  95. {
  96. break;
  97. }
  98. string str = Encoding.UTF8.GetString(buffer, 0, len);
  99. Debug.Log("接收到的消息:" + socketSend.RemoteEndPoint + ":" + str);
  100. recMes = str;
  101. recTimes++;
  102. info = "接收到一次数据,接收次数为:" + recTimes;
  103. Debug.Log("接收数据次数:" + recTimes);
  104. }
  105. }
  106. catch { }
  107. }
  108. // 服务器端不停的向客户端发送消息
  109. void SendMessage(object o)
  110. {
  111. try
  112. {
  113. Socket socketSend = o as Socket;
  114. while (true)
  115. {
  116. if (isSendData)
  117. {
  118. isSendData = false;
  119. byte[] sendByte = Encoding.UTF8.GetBytes(inputMessage);
  120. Debug.Log("发送的数据为 :" + inputMessage);
  121. Debug.Log("发送的数据字节长度 :" + sendByte.Length);
  122. // 6.发送消息
  123. socketSend.Send(sendByte);
  124. }
  125. }
  126. }
  127. catch { }
  128. }
  129. // 关闭连接,释放资源
  130. private void OnDisable()
  131. {
  132. Debug.Log("begin OnDisable()");
  133. if (clickConnectBtn)
  134. {
  135. try
  136. {
  137. // 7.关闭Socket
  138. socketWatch.Shutdown(SocketShutdown.Both); //禁用Socket的发送和接收功能
  139. socketWatch.Close(); //关闭Socket连接并释放所有相关资源
  140. socketSend.Shutdown(SocketShutdown.Both); //禁用Socket的发送和接收功能
  141. socketSend.Close(); //关闭Socket连接并释放所有相关资源
  142. }
  143. catch (Exception e)
  144. {
  145. Debug.Log(e.Message);
  146. }
  147. }
  148. Debug.Log("end OnDisable()");
  149. }
  150. //交互界面(代码创建)
  151. void OnGUI()
  152. {
  153. GUI.color = Color.black; //字体颜色
  154. GUI.Label(new Rect(65, 10, 80, 20), "状态信息");
  155. GUI.Label(new Rect(155, 10, 80, 70), info);
  156. GUI.Label(new Rect(65, 80, 80, 20), "接收到消息:");
  157. GUI.Label(new Rect(155, 80, 80, 20), recMes);
  158. GUI.Label(new Rect(65, 120, 80, 20), "发送的消息:");
  159. inputMessage = GUI.TextField(new Rect(155, 120, 100, 20), inputMessage, 20);
  160. GUI.Label(new Rect(65, 160, 80, 20), "本机ip地址:");
  161. inputIp = GUI.TextField(new Rect(155, 160, 100, 20), inputIp, 20);
  162. GUI.Label(new Rect(65, 200, 80, 20), "本机端口号:");
  163. inputPort = GUI.TextField(new Rect(155, 200, 100, 20), inputPort, 20);
  164. if (GUI.Button(new Rect(65, 240, 60, 20), "开始监听"))
  165. {
  166. ClickConnect(); //点击开始
  167. }
  168. if (GUI.Button(new Rect(65, 280, 60, 20), "发送数据"))
  169. {
  170. isSendData = true; //发送数据
  171. }
  172. }
  173. }

3.2 客户端

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.IO;
  8. using System.Threading;
  9. using UnityEngine;
  10. using UnityEngine.UI;
  11. public class TCPClient : MonoBehaviour
  12. {
  13. public string staInfo = "NULL"; //状态信息
  14. public string inputIp = "127.0.0.1"; //输入ip地址
  15. public string inputPort = "8080"; //输入端口号
  16. public string inputMes = "NULL"; //发送的消息
  17. public int recTimes = 0; //接收到信息的次数
  18. public string recMes = "NULL"; //接收到的消息
  19. public Socket socketSend; //客户端套接字,用来链接远端服务器
  20. public bool clickSend = false; //是否点击发送按钮
  21. void Start()
  22. {
  23. }
  24. // Update is called once per frame
  25. void Update()
  26. {
  27. }
  28. //建立链接
  29. public void ClickConnect()
  30. {
  31. try
  32. {
  33. int _port = Convert.ToInt32(inputPort); //获取端口号
  34. string _ip = inputIp; //获取ip地址
  35. // 1.创建一个Socket对象(和服务端进行通讯)
  36. socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  37. IPAddress ip = IPAddress.Parse(_ip);
  38. IPEndPoint point = new IPEndPoint(ip, _port);
  39. // 2.连接服务器
  40. socketSend.Connect(point);
  41. Debug.Log("连接成功 , " + " ip = " + ip + " port = " + _port);
  42. staInfo = ip + ":" + _port + " 连接成功";
  43. Thread r_thread = new Thread(Received); //开启新的线程,不停的接收服务器发来的消息
  44. r_thread.IsBackground = true;
  45. r_thread.Start();
  46. Thread s_thread = new Thread(SendMessage); //开启新的线程,不停的给服务器发送消息
  47. s_thread.IsBackground = true;
  48. s_thread.Start();
  49. }
  50. catch (Exception)
  51. {
  52. Debug.Log("IP或者端口号错误......");
  53. staInfo = "IP或者端口号错误......";
  54. }
  55. }
  56. /// <summary>
  57. /// 接收服务端返回的消息
  58. /// </summary>
  59. void Received()
  60. {
  61. while (true)
  62. {
  63. try
  64. {
  65. byte[] buffer = new byte[1024 * 6];
  66. //实际接收到的有效字节数
  67. // 3.接受消息
  68. int len = socketSend.Receive(buffer);
  69. if (len == 0)
  70. {
  71. break;
  72. }
  73. recMes = Encoding.UTF8.GetString(buffer, 0, len);
  74. Debug.Log("客户端接收到的数据 : " + recMes);
  75. recTimes++;
  76. staInfo = "接收到一次数据,接收次数为 :" + recTimes;
  77. Debug.Log("接收次数为:" + recTimes);
  78. }
  79. catch { }
  80. }
  81. }
  82. /// <summary>
  83. /// 向服务器发送消息
  84. /// </summary>
  85. /// <param name="sender"></param>
  86. /// <param name="e"></param>
  87. void SendMessage()
  88. {
  89. try
  90. {
  91. while (true)
  92. {
  93. if (clickSend) //如果点击了发送按钮
  94. {
  95. clickSend = false;
  96. string msg = inputMes;
  97. byte[] buffer = new byte[1024 * 6];
  98. buffer = Encoding.UTF8.GetBytes(msg);
  99. // 4.发送消息
  100. socketSend.Send(buffer);
  101. Debug.Log("发送的数据为:" + msg);
  102. }
  103. }
  104. }
  105. catch { }
  106. }
  107. private void OnDisable()
  108. {
  109. Debug.Log("begin OnDisable()");
  110. if (socketSend == null) return;
  111. if (socketSend.Connected)
  112. {
  113. try
  114. {
  115. // 5.关闭Socket
  116. socketSend.Shutdown(SocketShutdown.Both); //禁用Socket的发送和接收功能
  117. socketSend.Close(); //关闭Socket连接并释放所有相关资源
  118. }
  119. catch (Exception e)
  120. {
  121. print(e.Message);
  122. }
  123. }
  124. Debug.Log("end OnDisable()");
  125. }
  126. //用户界面
  127. void OnGUI()
  128. {
  129. GUI.color = Color.black;
  130. GUI.Label(new Rect(65, 10, 60, 20), "状态信息");
  131. GUI.Label(new Rect(135, 10, 80, 60), staInfo);
  132. GUI.Label(new Rect(65, 70, 50, 20), "服务器ip地址");
  133. inputIp = GUI.TextField(new Rect(125, 70, 100, 20), inputIp, 20);
  134. GUI.Label(new Rect(65, 110, 50, 20), "服务器端口");
  135. inputPort = GUI.TextField(new Rect(125, 110, 100, 20), inputPort, 20);
  136. GUI.Label(new Rect(65, 150, 80, 20), "接收到消息:");
  137. GUI.Label(new Rect(155, 150, 80, 20), recMes);
  138. GUI.Label(new Rect(65, 190, 80, 20), "发送的消息:");
  139. inputMes = GUI.TextField(new Rect(155, 190, 100, 20), inputMes, 20);
  140. if (GUI.Button(new Rect(65, 230, 60, 20), "开始连接"))
  141. {
  142. ClickConnect();
  143. }
  144. if (GUI.Button(new Rect(65, 270, 60, 20), "发送信息"))
  145. {
  146. clickSend = true;
  147. }
  148. }
  149. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/861350
推荐阅读
相关标签
  

闽ICP备14008679号