unity3d游戏开发之实现基于Socket通讯的公共聊天室

  • 格式:doc
  • 大小:154.00 KB
  • 文档页数:5

由于这段时间比较忙,所以也很久没发布过新的教程,这几天刚好要为一个项目写服务端程序,所以顺便也在Unity3d里面实现了一个简单的客户端,多个客户端一同使用就是一个简单的公共聊天室了。

服务端为一个控制台程序使用C#实现,当然,在Unity3d中也相应地使用了C#语言实现客户端,服务端和客户端能实现消息的互通,当服务端接收到某客户端发送过来的消息时将会对客户端列表成员进行广播,这是公共聊天室的最基本的形式。

Socket通讯是网络游戏最为基础的知识,因此这个实例能向有志投身于网游行业的初学者提供指导意义。

这篇文章来自
ing System;
ing ;
ing ;
ing TestServer
5.{
6. class Program
7. {
8. .\n");
9.
10. .\n");
11. }
12. }
13. }
14.}
ing System;
ing ;
ing ;
ing ;
ing TestServer
6.{
7. class ChatClient
8. {
9. public static Hashtable ALLClients = new Hashtable();
eginRead(data, 0, ReceiveMessage, null);
10. }
11.
12. ;
13.
14. ;
15. }
16. }
17.
18. endMessage(message + ;
19. }
20. }
21.
22. }
23.}
Unity3d客户端的代码:
ing UnityEngine;
ing ;
3.
ing System;
ing ;
ing ;
ing class ClientHandler : MonoBehaviour
8.{
9. const int portNo = 500;
10. private TcpClient _client;
11. byte[] data;
12.
13. // Use this for initialization
14. void Start ()
15. {
16.
17. }
18.
19. // Update is called once per frame
20. void Update ()
21. {
22.
23. }
24.
25. public string nickName = "";
26. public string message = "";
27. public string sendMsg = "";
28.
29. void OnGUI()
30. {
31. nickName = (new Rect(10, 10, 100, 20), nickName);
32. message = (new Rect(10, 40, 300, 200), message);
33. sendMsg = (new Rect(10, 250, 210, 20), sendMsg);
34.
35. if(new Rect(120, 10, 80, 20), "Connect"))
36. {
37. //("hello");
38.
39. = new TcpClient();
40. "", portNo);
41.
42. data = new byte[ //SendMessage;
43. SendMessage(nickName);
44.
45. 0, ReceiveMessage, null);
46. };
47.
48. if(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. {
workStream ns = byte[] data
= (data, 0, ;
60. ();
61. }
62. catch (Exception ex)
63. {
64. //());
65. }
66. }
67.
68. public void ReceiveMessage(IAsyncResult ar)
69. {
70. try
71. {
72. int bytesRead;
73.
74. bytesRead = if (bytesRead < 1)
75. {
76. return;
77. }
78. else
79. {
80.
81. 0, bytesRead));
82.
83. message += 0, bytesRead);
84. }
85.
86. 0, ReceiveMessage, null);
87.
88.
89. }
90. catch (Exception ex)
91. {
92.
93. }
94. }
95.}。