unity3d游戏开发之实现基于Socket通讯公共聊天室
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
由于这段时间比较忙,所以也很久没发布过新的教程,这几天刚好要为一个项目写服务端程序,所以顺便也在Unity3d里面实现了一个简单的客户端,多个客户端一同使用就是一个简单的公共聊天室了。服务端为一个控制台程序使用C#实现,当然,在Unity3d中也相应地使用了C#语言实现客户端,服务端和客户端能实现消息的互通,当服务端接收到某客户端发送过来的消息时将会对客户端列表成员进行广播,这是公共聊天室的最基本的形式。Socket通讯是网络游戏最为基础的知识,因此这个实例能向有志投身于网游行业的初学者提供指导意义。
这篇文章来自狗刨学习网
Program.cs
ing System;
ing System.Collections.Generic;
ing System.Linq;
ing System.Text;
ing .Sockets;
6.
space TestServer
8.{
9.class Program
10.{
11. // 设置连接端口
12. const int portNo = 500;
13.
14. static void Main(string[] args)
15. {
16. // 初始化服务器IP
17. .IPAddress localAdd = .IPAddress.Parse("127.0.0.1");
18.
19. // 创建TCP侦听器
20. TcpListener listener = new TcpListener(localAdd, portNo);
21.
22. listener.Start();
23.
24. // 显示服务器启动信息
25. Console.WriteLine("Server is starting...\n");
26.
27. // 循环接受客户端的连接请求
28. while (true)
29. {
30.ChatClient user = new ChatClient(listener.AcceptTcpClient());
31.
32.// 显示连接客户端的IP与端口
33.Console.WriteLine(user._clientIP + " is joined...\n");
34. }
35. }
36.}
37.}
ChatClient.cs
ing System;
ing System.Collections.Generic;
ing System.Linq;
ing System.Text;
ing System.Collections;
ing .Sockets;
7.
space TestServer
9.{
10.class ChatClient
11.{
12. public static Hashtable ALLClients = new Hashtable(); // 客户列表
13.
14. private TcpClient _client; // 客户端实体
15. public string _clientIP; // 客户端IP
16. private string _clientNick; // 客户端昵称
17.
18. private byte[] data; // 消息数据
19.
20. private bool ReceiveNick = true;
21.
22. public ChatClient(TcpClient client)
23. {
24. this._client = client;
25.
26. this._clientIP = client.Client.RemoteEndPoint.ToString();
27.
28. // 把当前客户端实例添加到客户列表当中
29. ALLClients.Add(this._clientIP, this);
30.
31. data = new byte[this._client.ReceiveBufferSize];
32.
33. // 从服务端获取消息
34. client.GetStream().BeginRead(data, 0,
System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
35. }
36.
37. // 从客戶端获取消息
38. public void ReceiveMessage(IAsyncResult ar)
39. {
40. int bytesRead;
41.
42. try
43. {
44.lock (this._client.GetStream())
45.{
46. bytesRead = this._client.GetStream().EndRead(ar);
47.}
48.
49.if (bytesRead < 1)
50.{
51. ALLClients.Remove(this._clientIP);
52.
53. Broadcast(this._clientNick + " has left the chat");
54.
55. return;
56.}
57.else
58.{
59. string messageReceived = System.T ext.Encoding.ASCII.GetString(data, 0,
bytesRead);
60.
61. if (ReceiveNick)
62. {
63. this._clientNick = messageReceived;
64.
65. Broadcast(this._clientNick + " has joined the chat.");
66.
67. //this.sendMessage("hello");
68.
69. ReceiveNick = false;
70. }
71. else
72. {
73. Broadcast(this._clientNick + ">" + messageReceived);
74.
75. }
76.}
77.