效果展示(尚未完善)

UDP实现一个简易的聊天室 (Unity&&C#完成)

UDP

User Data Protocol 用户数据报协议

概述

UDP不连接的数据报模式。即传输数据之前源端和终端不建立连接使用尽最大努力交付原则,即不保证可靠交付

数据报模式:由于不建立连接,收到的数据可能是任意主机发送的,所以接收端Read次数必须与发送端Write次数相同,每次只接收一个报文,避免多个报文合并如果报文过长多出部分会被丢弃,所以注意数据最大为1472字节

 

实现步骤

 

服务端                                                客户端

获取本机终结点                                  获取本机终结点

创建UdpClient对象                              创建UdpClient对象                                   

接收任意终结点消息                             接收任意终结点消息

向客户端发送消息                               向服务端发送消息

……                                                    … 

关闭连接                                           关闭连接

 

ChatUDPClientTest
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Common;
using UIWidgetsSamples;
using System;

/// <summary>
/// 服务端
/// </summary>
public class ChatUDPServerTest : MonoBehaviour
{
    public string serverIP;
    //IP地址
    public int serverPort;
    //端口
    //1.创建Scoket对象 IP Port
    private Thread thread;
    private UdpClient udpSeivic;
    public void Start()
    {
        chatView = transform.FindChildByName("ChatView").
            GetComponent<ChatView>();
        //给端口和IP
        //构建终结点  IP和一个端口
        IPEndPoint localEP = new 
            IPEndPoint(IPAddress.Parse(serverIP), serverPort);
        udpSeivic = new UdpClient(localEP);

        thread = new Thread(ReceiveMessage);
        thread.Start();
    }
    
    /// <summary>
    /// 接收消息
    /// </summary>
    private void ReceiveMessage()
    {
        while (true)
        {
            IPEndPoint remote = new
                IPEndPoint(IPAddress.Any, 0);
            //创建任意终结点
            //ref
            byte[] date = udpSeivic.Receive(ref remote);
            //Receive接收消息  如果没有收到消息 线程阻塞  放在线程中
            string msg = Encoding.UTF8.GetString(date);
            //获取的客户都安信息
            Debug.Log(remote.Address + "===" + remote.Port);
            //如果接收客户端的消息,会把任意终结点修改为客户端的终结点
            ThreadCrossHelper.Instance.ExecuteOnMainThread(() => { ShowMessage(msg); });
        }
    }
    private ChatView chatView;
    /// <summary>
    /// 显示消息
    /// </summary>
    /// <param name="msg"></param>
    public void ShowMessage(string msg)
    {
        chatView.DataSource.Add(new ChatLine()
        {
            UserName = "AnnnS",
            Message = msg,
            Time = DateTime.Now,
            Type = ChatLineType.User,
        });
    }
    private void OnApplicationQuit()
    {
        udpSeivic.Close();
        thread.Abort();
    }
}
ChatUDPServerTest

相关文章:

  • 2022-02-09
  • 2022-12-23
  • 2021-08-17
  • 2021-12-22
  • 2021-11-28
  • 2022-12-23
  • 2022-12-23
  • 2021-07-11
猜你喜欢
  • 2022-12-23
  • 2021-04-09
  • 2021-09-13
  • 2021-09-15
  • 2022-12-23
  • 2021-06-10
相关资源
相似解决方案