赞
踩
需要源码请点赞关注收藏后评论区留言并且私信~~~
下面利用Unity和C#语言做一个简单的聊天室程序,主要用到的技术就是Socket通信连接,需要一个客户端和一个服务器端,服务器端就使用C#语言的控制台完成
下面就开始搭建C#语言服务器端
1:新建一个C#语言控制台程序
2:命名项目为Server 右击项目新建项
3:新建类MessageData.cs ClientController.cs MessageData类存放指定的消息协议,每一条消息都由创建消息对象,设置消息类型和消息内容组成,服务器端和客户端都必须配置这个消息协议
ClientController脚本用来控制所有的客户端程序
部分代码如下
- using System;
- using System.Net.Sockets;
- using System.Threading;
-
- namespace Server
- {
- class ClientController
- {
- /// <summary>
- /// 用户链接的通道
- /// </summary>
- private Socket clientSocket;
- //接收的线程
- Thread receiveThread;
- /// <summary>
- /// 昵称
- /// </summary>
- public string nickName;
- public ClientController(Socket socket)
- {
- clientSocket = socket;
- //启动接收的方法
- //开始收的线程
- receiveThread = new Thread(ReceiveFromClient);
- //启动收的线程
- receiveThread.Start();
- }
-
- /// <summary>
- /// 客户端连接 监听消息
- /// </summary>
- void ReceiveFromClient()
- {
- while (true)
- {
- byte[] buffer = new byte[512];
- int lenght = clientSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
- string json = System.Text.Encoding.UTF8.GetString(buffer, 0, lenght);
- json.TrimEnd();
- if (json.Length > 0)
- {
- Console.WriteLine("服务器接收内容:{0}", json);
- MessageData data = LitJson.JsonMapper.ToObject<MessageData>(json);
- switch (data.msgType)
- {
- case MessageType.Login://登陆
- nickName = data.msg;
- //1、通知客户端登陆成功
- MessageData backData = new MessageData();
- backData.msgType = MessageType.Login;
- backData.msg = "";
- SendToClient(backData);
- //2、通知所有客户端,XXX加入房间
- MessageData chatData = new MessageData();
- chatData.msgType = MessageType.Chat;
- chatData.msg = nickName + " 进入了房间";
- SendMessageDataToAllClientWithOutSelf(chatData);
- break;
- case MessageType.Chat://聊天
- MessageData chatMessageData = new MessageData();
- chatMessageData.msgType = MessageType.Chat;
- chatMessageData.msg = nickName + ":" + data.msg;
- SendMessageDataToAllClientWithOutSelf(chatMessageData);
- break;
- case MessageType.LogOut://退出
- //1、通知客户端,退出
- MessageData logOutData = new MessageData();
- logOutData.msgType = MessageType.LogOut;
- SendToClient(logOutData);
- //2、通知所有客户端,XXX退出了房间
- MessageData logOutChatData = new MessageData();
- logOutChatData.msgType = MessageType.Chat;
- logOutChatData.msg = nickName + " 退出了房间";
- SendMessageDataToAllClientWithOutSelf(logOutChatData);
- break;
- }
- }
- }
- }
-
- /// <summary>
- /// 向除了自身客户端的其他所有客户端广播消息
- /// </summary>
- /// <param name="data"></param>
- void SendMessageDataToAllClientWithOutSelf(MessageData data)
- {
- for (int i = 0; i < Program.clientControllerList.Count; i++)
- {
- if (Program.clientControllerList[i] != this)
- {
- Program.clientControllerList[i].SendToClient(data);
- }
- }
- }
-
- /// <summary>
- /// 发消息给客户端
- /// </summary>
- /// <param name="data">需要发送的内容</param>
- void SendToClient(MessageData data)
- {
- //把对象转换为json字符串
- string msg = LitJson.JsonMapper.ToJson(data);
- //把json字符串转换byte数组
- byte[] msgBytes = System.Text.Encoding.UTF8.GetBytes(msg);
- //发送消息
- int sendLength = clientSocket.Send(msgBytes);
- Console.WriteLine("服务器发送信息成功,发送信息内容:{0},长度{1}", msg, sendLength);
- Thread.Sleep(50);
- }
- }
- }
需要注意的是,这个脚本引用了一个LitJson程序包解析JSON数据,这个需要右击程序,选择管理NuGet程序包选项,在弹出的窗口中搜索LitJson然后安装即可
双击打开Program.cs脚本,这个脚本是C#语言控制台程序的主脚本,脚本中的一个Main函数是程序的入口函数 代码如下
- using System;
- using System.Collections.Generic;
- using System.Net;
- using System.Net.Sockets;
-
- namespace Server
- {
- class Program
- {
- /// <summary>
- /// 客户端管理列表
- /// </summary>
- public static List<ClientController> clientControllerList = new List<ClientController>();
- static void Main(string[] args)
- {
- //定义socket
- Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- //绑定IP和端口号
- IPEndPoint ipendPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
- Console.WriteLine("开始绑定端口号....");
- //将ip地址和端口号绑定
- serverSocket.Bind(ipendPoint);
- Console.WriteLine("绑定端口号成功,开启服务器....");
- //开启服务器
- serverSocket.Listen(100);
- Console.WriteLine("启动服务器{0}成功!", serverSocket.LocalEndPoint.ToString());
- while (true)
- {
- Console.WriteLine("等待连接.....");
- Socket clinetSocket = serverSocket.Accept();
- Console.WriteLine("客户端{0}成功连接", clinetSocket.RemoteEndPoint.ToString());
- ClientController controller = new ClientController(clinetSocket);
- //添加到列表中
- clientControllerList.Add(controller);
- Console.WriteLine("当前有{0}个用户", clientControllerList.Count);
- }
- }
- }
- }
服务器端目录结构如下
运行服务器端 启动正常会弹出一个窗口
Unity客户端搭建主要分为以下三个方面
1:搭建UI界面
2:制定消息协议
3:编写客户端
首先搭建UI界面 UI界面分为三部分,分别是初始界面,登录界面和聊天界面
搭建步骤省略 需要可点赞关注收藏后评论区留言私信 效果如下
在Unity中新建一个Plugins文件夹 里面存放代码文件和依赖 目录如下
整体运行效果如下
运行Unity客户端 出现两个聊天框 可以进行实时的聊天互动
C#控制台服务器端则会记录聊天的信息以及用户信息等等
部分代码如下
- using UnityEngine;
- using UnityEngine.UI;
-
- public class ChatUIController : MonoBehaviour
- {
- // 昵称
- public InputField nickNameInputField;
- //显示消息的文本
- public Text text;
- // 要发送的内容
- public InputField sendMsgInputField;
- // socket对象 代表客户端
- private ClientSocket clientSocket;
- //接收的消息
- private string receiveMsg;
- // 界面 0==loading 1==登陆 2==聊天
- public GameObject[] panels;
- //登录状态 0==loading 1==登陆 2==聊天
- private int LoadingState;
- void Start()
- {
- clientSocket = this.GetComponent<ClientSocket>();
- //委托和具体方法关联
- clientSocket.onConnectSuccess += OnSocketConnectSuccess;
- clientSocket.receiveMessageData += ReceiveMsgData;
- }
- void Update()
- {
-
- panels[0].SetActive(LoadingState == 0);
- panels[1].SetActive(LoadingState == 1);
- panels[2].SetActive(LoadingState == 2);
- }
- /// <summary>
- /// 发送按钮点击
- /// </summary>
- public void SendBtnClick()
- {
- if (sendMsgInputField != null && sendMsgInputField.text != "")
- {
- //发送
- clientSocket.PutMessageToQueue(sendMsgInputField.text);
- receiveMsg += "我:" + sendMsgInputField.text + "\n";
- //清理一下输入框内容
- sendMsgInputField.text = "";
- }
- }
- /// <summary>
- /// 加入房间按钮点击
- /// </summary>
- public void JoinInBtnClick()
- {
- if (nickNameInputField != null && nickNameInputField.text != "")
- {
- //创建数据对象
- MessageData data = new MessageData();
- data.msgType = MessageType.Login;
- data.msg = nickNameInputField.text;
- //发送数据对象
- clientSocket.PutMessageToQueue(data);
- }
- else
- {
- //提示
- Debug.Log("昵称不能为空!");
- }
- }
- /// <summary>
- /// 退出房间按钮点击事件
- /// </summary>
- public void LogOutBtnClick()
- {
- //消息数据
- MessageData data = new MessageData();
- data.msgType = MessageType.LogOut;
- //把消息传进去
- clientSocket.PutMessageToQueue(data);
- }
- /// <summary>
- /// 连接服务器成功的回调
- /// </summary>
- public void OnSocketConnectSuccess()
- {
- //进入登陆界面
- LoadingState = 1;
- }
- /// <summary>
- /// 接收消息的方法
- /// </summary>
- /// <param name="byteArray"></param>
- /// <param name="offset"></param>
- /// <param name="length"></param>
- public void ReceiveMsgData(byte[] byteArray, int offset, int length)
- {
- string msg = ClientSocket.ByteArrayToString(byteArray, offset, length);
- Debug.Log("收到信息:" + msg);
- //对信息进行处理
- MessageData data = LitJson.JsonMapper.ToObject<MessageData>(msg);
- switch (data.msgType)
- {
- case MessageType.Login://如果是登陆,代表界面可以切换了
- receiveMsg = "";
- LoadingState = 2;
- break;
- case MessageType.Chat://如果是聊天,代表进行聊天的显示
- receiveMsg += data.msg + "\n";
- break;
- case MessageType.LogOut://退出消息
- receiveMsg = "";
- LoadingState = 1;
- break;
- }
- }
- }
创作不易 觉得有帮助请点赞关注收藏~~~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。