经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C# » 查看文章
unity网络----简单基础
来源:cnblogs  作者:薄荷グ微凉べ  时间:2018/12/14 9:39:14  对本文有异议

网络

TCP:与打电话类似,通知服务到位

UDP:与发短信类似,消息发出即可

IP和端口号是网络两大重要成员

端口号(Port)分为知名端口号[0-1024,不开放)和动态端口号[1024,10000多,开放可用)

三次握手,四次挥手:

unity网端简单案例:

分为:综合管理部分、客户端和服务器

需要Socket作为媒介来进行交互

见代码:

 一、综合管理部分:

 

 

  1. 1 using System.Collections;
  2. 2 using System.Collections.Generic;
  3. 3 using UnityEngine;
  4. 4 using System.Net;
  5. 5 using System.Net.Sockets;
  6. 6 using System.Threading;
  7. 7 using System;
  8. 8
  9. 9 //综合管理部分
  10. 10 // 可以供客户端和服务器一块使用
  11. 11 public class TcpSocket
  12. 12 {
  13. 13 private Socket socket;//当前实例化的套接字
  14. 14 private byte[] data;//socket上的数据
  15. 15 private bool isServer; //用来区分服务器 还是客户端
  16. 16
  17. 17 //构造TcpSocket
  18. 18 public TcpSocket(Socket socket,int dataLength, bool isServer)
  19. 19 {
  20. 20 this.socket = socket;
  21. 21 data = new byte[dataLength];
  22. 22 this.isServer = isServer;
  23. 23 }
  24. 24 // 接受----->客户端
  25. 25 public void ClientReceive()
  26. 26 {
  27. 27 //data:数据缓存 0:接受位的偏移量 length
  28. 28 socket.BeginReceive(data,0,data.Length,SocketFlags.None,new AsyncCallback(ClientEndReceive),null);
  29. 29 }
  30. 30 public void ClientEndReceive(IAsyncResult ar)
  31. 31 {
  32. 32 int receiveLength = socket.EndReceive(ar); //数据的处理
  33. 33 string dataStr = System.Text.Encoding.UTF8.GetString(data,0, receiveLength); //把接受完毕的字节数组转化为 string类型
  34. 34 if (isServer)
  35. 35 { Debug.Log("服务器接受到了:" + dataStr);
  36. 36 for (int i = 0; i < Server.Instance.clients.Count; i++) //服务器要回什么
  37. 37 {
  38. 38 if (Server.Instance.clients[i].ClientConnect())
  39. 39 {
  40. 40 Server.Instance.clients[i].ClientSeed(System.Text.Encoding.UTF8.GetBytes("服务器回复:"+ dataStr));
  41. 41 }
  42. 42 }
  43. 43 }else {
  44. 44 DataManager.Instance.Msg = dataStr;
  45. 45 Debug.Log("客户端接受到了:" + dataStr);
  46. 46 }
  47. 47 }
  48. 48
  49. 49
  50. 50 // 发送---->客户端发送给服务器
  51. 51 public void ClientSeed(byte[] data)
  52. 52 {
  53. 53 socket.BeginSend(data,0, data.Length, SocketFlags.None,new AsyncCallback(ClientSeedEnd),null );
  54. 54 }
  55. 55
  56. 56 private void ClientSeedEnd(IAsyncResult ar)
  57. 57 {
  58. 58 socket.EndSend(ar);
  59. 59 }
  60. 60
  61. 61
  62. 62 //连接----客户端与服务器连接
  63. 63 public void ClientConnect(string ip,int port)
  64. 64 {
  65. 65 socket.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port),new AsyncCallback(ClientEndConnect),null);
  66. 66 }
  67. 67 public void ClientEndConnect(IAsyncResult ar)
  68. 68 {
  69. 69 if (ar.IsCompleted) {
  70. 70 Debug.Log("连接成功");
  71. 71 }
  72. 72 socket.EndConnect(ar);
  73. 73 }
  74. 74
  75. 75 // 客户端与服务器是否连接
  76. 76
  77. 77 public bool IsClientConnect()
  78. 78 {
  79. 79 return socket.Connected;
  80. 80 }
  81. 81 //断开连接
  82. 82 public void ClientClose()
  83. 83 {
  84. 84 if (socket!=null&& ISClientConnect())
  85. 85 {
  86. 86 socket.Close();
  87. 87 }
  88. 88 }
  89. 89
  90. 90 }
View Code

 

 二、服务器部分:

      注意:回调函数AcceptClient只有当服务器接受连接(连接成功了)才会被调用.

  1. 1 using System.Collections;
  2. 2 using System.Collections.Generic;
  3. 3 using UnityEngine;
  4. 4 using System.Net;
  5. 5 using System.Net.Sockets;
  6. 6 using System.Threading;
  7. 7 using System;
  8. 8
  9. 9 // 服务器
  10. 10
  11. 11 public class Server : MonoBehaviour {
  12. 12
  13. 13 //单例服务器,继承Mono的
  14. 14 private static Server instance;
  15. 15 public static Server Instance
  16. 16 {
  17. 17 get { return instance; }
  18. 18 }
  19. 19 private void Awake()
  20. 20 {
  21. 21 instance = this;
  22. 22 }
  23. 23 //------------------------------------------------------------------------
  24. 24 private Socket server;//定义一个服务器
  25. 25 public List<TcpSocket> clients;//所有连接的客户端
  26. 26 private bool isLoopAccept = true;//是否循环接受客户端的请求
  27. 27
  28. 28 void Start ()
  29. 29 {
  30. 30 //初始化服务器socket 协议族
  31. 31 server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
  32. 32 server.Bind(new IPEndPoint(IPAddress.Any,10086));//绑定端口号
  33. 33 server.Listen(100); //可以监听的客户端数目
  34. 34 //------------------------------------------------------------------------
  35. 35 //开辟一个线程 处理客户端连接请求 线程要暂停需用listenThread.Abort();
  36. 36 Thread listenThread = new Thread(ReceiveClient);
  37. 37 listenThread.Start(); //开启线程
  38. 38 listenThread.IsBackground = true; //后台运行
  39. 39 //------------------------------------------------------------------------
  40. 40 //初始化连接的客户端
  41. 41 clients = new List<TcpSocket>();
  42. 42
  43. 43 }
  44. 44
  45. 45 // 持续处理 接受客户端连接的请求
  46. 46 private void ReceiveClient()
  47. 47 {
  48. 48 while (isLoopAccept)
  49. 49 {
  50. 50 server.BeginAccept(AcceptClient,null); //开始接受客户端连接请求
  51. 51 Debug.Log("检测客户端连接中.....");
  52. 52 Thread.Sleep(1000);//每隔1s检测 有没有连接我
  53. 53 }
  54. 54 }
  55. 55 // 客户端连接成功之后回调
  56. 56 private void AcceptClient(IAsyncResult ar)
  57. 57 {
  58. 58 //连接成功后处理该客户
  59. 59 Socket client = server.EndAccept(ar);
  60. 60 TcpSocket clientSocket = new TcpSocket(client,1024,true);
  61. 61 clients.Add(clientSocket);
  62. 62 Debug.Log("连接成功");
  63. 63 }
  64. 64 //关闭项目终止线程,停止服务器.
  65. 65 private void OnApplicationQuit()
  66. 66 {
  67. 67 listenThread.Abort();
  68. 68 listenThread.IsBackground = true;//关闭线程
  69. 69 }
  70. 70 }
View Code

 

 三客户端部分:

 

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Threading;
  6. using System;
  7. using UnityEngine;
  8. using UnityEngine.UI;
  9. //客户端
  10. public class Client : MonoBehaviour {
  11. public InputField input;
  12. public Text receiveText;
  13. TcpSocket tcpClient;
  14. Socket client;
  15. void Start () {
  16. //注册监听事件
  17. receiveText = GameObject.Find("ReceiveText").GetComponent<Text>();
  18. tcpClient = new TcpSocket(client,1024,false);//初始化综合处理器
  19. client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//初始化客户端
  20. }
  21. void Update () {
  22. if (tcpClient != null && tcpClient.IsClientConnect())//如果客户端不为空且客户端已连接
  23. {
  24. tcpClient.ClientReceive();//执行综合管理器中的ClientReceive()
  25. }
  26. receiveText.text = DataManager.Instance.Msg;
  27. }
  28. public void OnClickConnectBtn()//客户端向服务器开始连接输入(IP和端口号)按钮事件
  29. {
  30. if (!tcpClient.IsClientConnect())
  31. {
  32. tcpClient.ClientConnect("10.50.6.129",10086);
  33. }
  34. }
  35. public void OnClickToSendServer()//客户端向服务器发送文本消息按钮事件
  36. {
  37. if (tcpClient != null && tcpClient.IsClientConnect() && !String.IsNullOrEmpty(input.text))
  38. {
  39. tcpClient.ClientSeed(System.Text.Encoding.UTF8.GetBytes(input.text));
  40. input.text = "";
  41. }
  42. }
  43. private void OnApplicationQuit()//关闭项目,退出服务器连接
  44. {
  45. if (tcpClient != null && tcpClient.ClientConnect())
  46. {
  47. tcpClient.ClientClose();
  48. }
  49. }
  50. }
View Code

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号