经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 软件/图像 » unity » 查看文章
Unity实现局域网聊天室功能
来源:jb51  时间:2021/10/11 9:22:35  对本文有异议

基于Unity实现一个简单的局域网聊天室,供大家参考,具体内容如下

学习Unity有一点时间了,之前学的都是做客户端的一些内容,现在开始学习联网。我的这个是在观看了 Siki 的教学内容来做的,也有自己的一点点小小的改动在里面。纯粹用于练手了。

因为本人也是小白一枚,所以,有错误的地方或者更好的实现方法,也希望有大神能帮忙指正,多谢!

整体过程分为两部分:构建服务端、构建客户端。

服务端:

大概思路:

1. 声明Socket连接以及绑定IP和端口,这里面使用

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net.Sockets;
  7. using System.Net;
  8.  
  9.  
  10. namespace ServerApplication
  11. {
  12. class Program
  13. {
  14. public static string IP;
  15. public static int Port;
  16. static List<Client> clientList = new List<Client>();
  17.  
  18. static Socket serverSocket;
  19.  
  20.  
  21. static void Main(string[] args)
  22. {
  23.  
  24. //绑定IP和端口
  25. BindIPAndPort();
  26. //
  27. while (true)
  28. {
  29. Socket clientSocket = serverSocket.Accept();
  30. Client client = new Client(clientSocket);
  31. clientList.Add(client);
  32. Console.WriteLine("一台主机进入连接");
  33. }
  34. }
  35.  
  36.  
  37.  
  38. /// <summary>
  39. /// 广播数据
  40. /// </summary>
  41. public static void BroadcostMSG(string s)
  42. {
  43. List<Client> NotConnectedList = new List<Client>();
  44. foreach (var item in clientList)
  45. {
  46. if(item.IsConnected)
  47. {
  48. item.SendMSG(s);
  49. }
  50. else
  51. {
  52. NotConnectedList.Add(item);
  53. }
  54.  
  55. }
  56.  
  57. foreach (var item in NotConnectedList)
  58. {
  59. clientList.Remove(item);
  60. }
  61.  
  62.  
  63. }
  64.  
  65.  
  66.  
  67. /// <summary>
  68. /// 绑定IP和端口
  69. /// </summary>
  70. public static void BindIPAndPort()
  71. {
  72.  
  73. //创建一个serverSocket
  74. serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  75.  
  76. //声明IP和端口
  77. Console.WriteLine("输入IP地址:");
  78. IP = Console.ReadLine();
  79. string ipStr = IP;
  80.  
  81.  
  82. Console.WriteLine("请输入端口:");
  83. Port = int.Parse(Console.ReadLine());
  84. int port = Port;
  85.  
  86. IPAddress serverIp = IPAddress.Parse(ipStr);
  87. EndPoint serverPoint = new IPEndPoint(serverIp, port);
  88.  
  89. //socket和ip进行绑定
  90. serverSocket.Bind(serverPoint);
  91.  
  92. //监听最大数为100
  93. serverSocket.Listen(100);
  94. }
  95. }
  96. }
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net.Sockets;
  7. using System.Threading;
  8.  
  9. namespace ServerApplication
  10. {
  11. class Client
  12. {
  13. public Socket clientSocket;
  14. //声明一个线程用于接收信息
  15. Thread t;
  16. //接收信息所用容器
  17. byte[] data = new byte[1024];
  18.  
  19. //构造函数
  20. public Client(Socket s)
  21. {
  22. clientSocket = s;
  23. t = new Thread(ReceiveMSG);
  24. t.Start();
  25. }
  26.  
  27. /// <summary>
  28. /// 接收数据
  29. /// </summary>
  30. void ReceiveMSG()
  31. {
  32. while(true)
  33. {
  34. if (clientSocket.Poll(10,SelectMode.SelectRead))
  35. {
  36. break;
  37. }
  38.  
  39. data = new byte[1024];
  40. int length = clientSocket.Receive(data);
  41. string message = Encoding.UTF8.GetString(data, 0, length);
  42.  
  43. Program.BroadcostMSG(message);
  44. Console.WriteLine("收到消息:" + message);
  45. }
  46.  
  47. }
  48.  
  49. /// <summary>
  50. /// 发送数据
  51. /// </summary>
  52. /// <param name="s"></param>
  53. public void SendMSG(string message)
  54. {
  55. byte[] data = Encoding.UTF8.GetBytes(message);
  56. clientSocket.Send(data);
  57. }
  58.  
  59.  
  60.  
  61. //判断此Client对象是否在连接状态
  62. public bool IsConnected
  63. {
  64. get { return clientSocket.Connected; }
  65. }
  66.  
  67. }
  68. }

客户端:

a.UI界面

UI界面是使用UGUI实现的
登录用户可以自己取名进行登录(发言时用于显示),使用时需要输入服务端的IP地址和端口号

下面是聊天室的页面,在输入框内输入要发送的消息,点击Send,将信息发送出去

这是服务端的信息

b.关于客户端的脚本

(1)这是ClientManager,负责与服务端进行连接,通信

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.Net.Sockets;
  5. using System.Net;
  6. using System.Text;
  7. using UnityEngine.UI;
  8. using System.Threading;
  9. public class ClientManager : MonoBehaviour
  10. {
  11. //ip:192.168.1.7
  12. public string ipAddressstr;
  13. public int port;
  14. public Text ipTextToShow;
  15. //Socket
  16. private Socket ClientServer;
  17.  
  18. //文本输入框
  19. public InputField inputTxt;
  20. public string inputMSGStr;
  21.  
  22. //接收
  23. Thread t;
  24. public Text receiveTextCom;
  25. public string message;
  26.  
  27. // Use this for initialization
  28. void Start()
  29. {
  30. ipTextToShow.text = ipAddressstr;
  31. // ConnectedToServer();
  32.  
  33. }
  34.  
  35. // Update is called once per frame
  36. void Update()
  37. {
  38. if (message != null && message != "")
  39. {
  40. receiveTextCom.text = receiveTextCom.text + "\n" + message;
  41. message = "";
  42. }
  43. }
  44.  
  45.  
  46. /// <summary>
  47. /// 连接服务器
  48. /// </summary>
  49. public void ConnectedToServer()
  50. {
  51. ClientServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  52.  
  53. //声明IP地址和端口
  54. IPAddress ServerAddress = IPAddress.Parse(ipAddressstr);
  55. EndPoint ServerPoint = new IPEndPoint(ServerAddress, port);
  56.  
  57. ipAddressstr = IpInfo.ipStr;
  58. port = IpInfo.portStr;
  59.  
  60.  
  61. //开始连接
  62. ClientServer.Connect(ServerPoint);
  63.  
  64. t = new Thread(ReceiveMSG);
  65. t.Start();
  66.  
  67. }
  68.  
  69.  
  70. /// <summary>
  71. /// 接收消息
  72. /// </summary>
  73. /// <returns>“string”</returns>
  74. void ReceiveMSG()
  75. {
  76. while (true)
  77. {
  78. if (ClientServer.Connected == false)
  79. {
  80. break;
  81. }
  82. byte[] data = new byte[1024];
  83. int length = ClientServer.Receive(data);
  84. message = Encoding.UTF8.GetString(data, 0, length);
  85. //Debug.Log("有消息进来");
  86.  
  87. }
  88.  
  89. }
  90.  
  91.  
  92. /// <summary>
  93. /// 发送string类型数据
  94. /// </summary>
  95. /// <param name="input"></param>
  96. public void SendMSG()
  97. {
  98.  
  99. Debug.Log("button Clicked");
  100. //message = "我:" + inputTxt.text;
  101. inputMSGStr = inputTxt.text;
  102. byte[] data = Encoding.UTF8.GetBytes(IpInfo.name+":"+inputMSGStr);
  103. ClientServer.Send(data);
  104.  
  105. }
  106.  
  107. private void OnDestroy()
  108. {
  109. ClientServer.Shutdown(SocketShutdown.Both);
  110. ClientServer.Close();
  111. }
  112. private void OnApplicationQuit()
  113. {
  114. OnDestroy();
  115. }
  116. }

(2)SceneManager,用于场景切换,这里只是利用GameObject进行SetActive()来实现,并不是创建了单独的Scene进行管理。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class SceneManager : MonoBehaviour {
  6.  
  7.  
  8. public GameObject loginPanel;
  9. public GameObject communicatingPanel;
  10. // Use this for initialization
  11.  
  12. public void OnSwitch()
  13. {
  14. loginPanel.SetActive(false);
  15. communicatingPanel.SetActive(true);
  16. }
  17. }

(3)LogInPanel和IPInfo,一个挂载在登录界面上,一个是数据模型,用于存储数据。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class LogInPanel : MonoBehaviour {
  7.  
  8.  
  9. public Text nameInputTxt;
  10. public Text ipInputTxt;
  11. public Text portInputTxt;
  12.  
  13.  
  14. //private string name;
  15. //private string ipStr;
  16. //private string portStr;
  17.  
  18.  
  19. public void OnLogInClick()
  20. {
  21. IpInfo.name = nameInputTxt.text;
  22. IpInfo.ipStr = ipInputTxt.text;
  23. IpInfo.portStr = int.Parse(portInputTxt.text);
  24. }
  25.  
  26.  
  27.  
  28. }
  1. public static class IpInfo {
  2.  
  3. public static string name;
  4. public static string ipStr;
  5. public static int portStr;
  6.  
  7. }

总结:第一次写学习博,还有很多地方要学习啊。

留待解决的问题:此聊天室只能用于局域网以内,广域网就无法实现通信了,还要看看怎么实现远程的一个通信,不然这个就没有存在的意义了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

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

本站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号