Unity3D教程:实现基于Socket通讯的公共聊天室

来源:互联网 发布:太空工程师 编程 编辑:程序博客网 时间:2024/05/01 22:51

多个客户端一同使用就是一个简单的公共聊天室。服务端为一个控制台程序使用C#实现,当然,在Unity3D中也相应地使用了C#语言实现客户端,服务端和客户端能实现消息的互通,当服务端接收到某客户端发送过来的消息时将会对客户端列表成员进行广播,这是公共聊天室的最基本的形式。Socket通讯是网络游戏最为基础的知识,因此这个实例能向有志投身于网游行业的初学者提供指导意义。

[csharp] view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Net.Sockets;  
  6. namespace TestServer  
  7. {  
  8. class Program  
  9. {  
  10. // 设置连接端口  
  11. const int portNo = 500;  
  12. static void Main(string[] args)  
  13. {  
  14. // 初始化服务器IP  
  15. System.Net.IPAddress localAdd = System.Net.IPAddress.Parse("127.0.0.1");  
  16. // 创建TCP侦听器  
  17. TcpListener listener = new TcpListener(localAdd, portNo);  
  18. listener.Start();  
  19. // 显示服务器启动信息  
  20. Console.WriteLine("Server is starting...\n");  
  21. // 循环接受客户端的连接请求  
  22. while (true)  
  23. {  
  24. ChatClient user = new ChatClient(listener.AcceptTcpClient());  
  25. // 显示连接客户端的IP与端口  
  26. Console.WriteLine(user._clientIP + " is joined...\n");  
  27. }  
  28. }  
  29. }  
  30. }  

ChatClient.cs

[csharp] view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Collections;  
  6. using System.Net.Sockets;  
  7. namespace TestServer  
  8. {  
  9. class ChatClient  
  10. {  
  11. public static Hashtable ALLClients = new Hashtable(); // 客户列表  
  12. private TcpClient _client;  // 客户端实体  
  13. public  string _clientIP;   // 客户端IP  
  14. private string _clientNick; // 客户端昵称  
  15. private byte[] data;        // 消息数据  
  16. private bool ReceiveNick = true;  
  17. public ChatClient(TcpClient client)  
  18. {  
  19. this._client = client;  
  20. this._clientIP = client.Client.RemoteEndPoint.ToString();  
  21. // 把当前客户端实例添加到客户列表当中  
  22. ALLClients.Add(this._clientIP, this);  
  23. data = new byte[this._client.ReceiveBufferSize];  
  24. // 从服务端获取消息  
  25. client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);  
  26. }  
  27. // 从客戶端获取消息  
  28. public void ReceiveMessage(IAsyncResult ar)  
  29. {  
  30. int bytesRead;  
  31. try  
  32. {  
  33. lock (this._client.GetStream())  
  34. {  
  35. bytesRead = this._client.GetStream().EndRead(ar);  
  36. }  
  37. if (bytesRead < 1)  
  38. {  
  39. ALLClients.Remove(this._clientIP);  
  40. Broadcast(this._clientNick + " has left the chat");  
  41. return;  
  42. }  
  43. else  
  44. {  
  45. string messageReceived = System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);  
  46. if (ReceiveNick)  
  47. {  
  48. this._clientNick = messageReceived;  
  49. Broadcast(this._clientNick + " has joined the chat.");  
  50. //this.sendMessage("hello");  
  51. ReceiveNick = false;  
  52. }  
  53. else  
  54. {  
  55. Broadcast(this._clientNick + ">" + messageReceived);  
  56. }  
  57. }  
  58. lock (this._client.GetStream())  
  59. {  
  60. this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);  
  61. }  
  62. }  
  63. catch (Exception ex)  
  64. {  
  65. ALLClients.Remove(this._clientIP);  
  66. Broadcast(this._clientNick + " has left the chat.");  
  67. }  
  68. }  
  69. // 向客戶端发送消息  
  70. public void sendMessage(string message)  
  71. {  
  72. try  
  73. {  
  74. System.Net.Sockets.NetworkStream ns;  
  75. lock (this._client.GetStream())  
  76. {  
  77. ns = this._client.GetStream();  
  78. }  
  79. // 对信息进行编码  
  80. byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(message);  
  81. ns.Write(bytesToSend, 0, bytesToSend.Length);  
  82. ns.Flush();  
  83. }  
  84. catch (Exception ex)  
  85. {  
  86.   
  87. }  
  88. }  
  89. // 向客户端广播消息  
  90. public void Broadcast(string message)  
  91. {  
  92. Console.WriteLine(message);  
  93. foreach (DictionaryEntry c in ALLClients)  
  94. {  
  95. ((ChatClient)(c.Value)).sendMessage(message + Environment.NewLine);  
  96. }  
  97. }  
  98. }  
  99. }  


Unity3d客户端的代码ClientHandler.cs

[csharp] view plain copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.ComponentModel;  
  6. using System.Text;  
  7. using System.Net.Sockets;  
  8. public class ClientHandler : MonoBehaviour  
  9. {  
  10. const int portNo = 500;  
  11. private TcpClient _client;  
  12. byte[] data;  
  13.   
  14. // Use this for initialization  
  15. void Start ()  
  16. {  
  17.   
  18. }  
  19.   
  20. // Update is called once per frame  
  21. void Update ()  
  22. {  
  23.   
  24. }  
  25.   
  26. public string nickName = "";  
  27. public string message = "";  
  28. public string sendMsg = "";  
  29.   
  30. void OnGUI()  
  31. {  
  32. nickName = GUI.TextField(new Rect(10, 10, 100, 20), nickName);  
  33. message = GUI.TextArea(new Rect(10, 40, 300, 200), message);  
  34. sendMsg = GUI.TextField(new Rect(10, 250, 210, 20), sendMsg);  
  35.   
  36. if(GUI.Button(new Rect(120, 10, 80, 20), "Connect"))  
  37. {  
  38. //Debug.Log("hello");  
  39.   
  40. this._client = new TcpClient();  
  41. this._client.Connect("127.0.0.1", portNo);  
  42. data = new byte[this._client.ReceiveBufferSize];  
  43. //SendMessage(txtNick.Text);  
  44. SendMessage(nickName);  
  45. this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);  
  46. };  
  47.   
  48. if(GUI.Button(new Rect(230, 250, 80, 20), "Send"))  
  49. {  
  50. SendMessage(sendMsg);  
  51. sendMsg = "";  
  52. };  
  53. }  
  54.   
  55. public void SendMessage(string message)  
  56. {  
  57. try  
  58. {  
  59. NetworkStream ns = this._client.GetStream();  
  60. byte[] data = System.Text.Encoding.ASCII.GetBytes(message);  
  61. ns.Write(data, 0, data.Length);  
  62. ns.Flush();  
  63. }  
  64. catch (Exception ex)  
  65. {  
  66. //MessageBox.Show(ex.ToString());  
  67. }  
  68. }  
  69.   
  70. public void ReceiveMessage(IAsyncResult ar)  
  71. {  
  72. try  
  73. {  
  74. int bytesRead;  
  75. bytesRead = this._client.GetStream().EndRead(ar);  
  76. if (bytesRead < 1)  
  77. {  
  78. return;  
  79. }  
  80. else  
  81. {  
  82.   
  83. Debug.Log(System.Text.Encoding.ASCII.GetString(data, 0, bytesRead));  
  84.   
  85. message += System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);  
  86. }  
  87. this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);  
  88.   
  89. }  
  90. catch (Exception ex)  
  91. {  
  92.   
  93. }  
  94. }  
  95. }  

 版权声明:转载时请以超链接形式标明文章原始出处和作者信息

0 0
原创粉丝点击