Unity Socket UDP

using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Text;


public class SocketUDPServer
{
    private string ip = "127.0.0.1";
    private int port = 5690;
    private Socket socket;
    private static SocketUDPServer socketServer;
    public List<string> listMessage = new List<string>();

    public static SocketUDPServer getInstance()
    {
        if (socketServer == null)
        {
            socketServer = new SocketUDPServer();
            socketServer.Init();
        }
        return socketServer;
    }

    private void Init()
    {
        IPAddress ipAddress = IPAddress.Parse(ip);
        IPEndPoint IPE = new IPEndPoint(ipAddress,port);
        //Udp搭配SocketType.Dgram   Tcp搭配SocketType.Stream
        socket=new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
        socket.Bind(IPE);
        Thread threadReceive = new Thread(new ThreadStart(ReceiveMessage));
        threadReceive.Start();
    }
    private void ReceiveMessage()
    {
        while (true)
        {
            byte[] buff = new byte[1024];
            int iBytes = socket.Receive(buff, SocketFlags.None);
            if (iBytes <= 0)
                break;
            string strGetMessage = Encoding.ASCII.GetString(buff, 0, iBytes);
            listMessage.Add(strGetMessage);
        }
    }
    public void  Close()
    {
        if(socket!=null)
            socket.Close();
    }
   

}

Unity是一款跨平台的游戏引擎,它可以用于开发游戏应用程序。在Unity中,可以使用TCP和UDP协议进行网络通信。 TCP和UDP是用于通过Internet发送信息的两种协议。TCP(传输控制协议)是一种可靠的协议,它通过建立连接、数据分段、校验和等机制,确保数据正确地从发送端传输到接收端。而UDP(用户数据报协议)是一种不可靠的协议,它没有建立连接的过程,数据被分割成数据报并发送出去,但不保证接收端能够正确接收所有数据。 在Unity中,可以使用Socket接口来实现TCP和UDP的通信。Socket接口是TCP/IP网络的API,它定义了许多函数或例程,用于开发TCP/IP网络上的应用程序。通过使用Socket接口,可以在Unity中实现TCP和UDP的服务端和客户端。 要在Unity中实现TCP服务端,可以使用Socket类的相关方法来监听客户端的连接,并接收和发送数据。具体的实现可以参考引用中的内容。 要在Unity中实现TCP客户端,可以使用Socket类的相关方法来连接服务端,并发送和接收数据。具体的实现可以参考引用中的内容。 要在Unity中实现UDP服务端,可以使用Socket类的相关方法来接收和发送数据报。具体的实现可以参考引用中的内容。 要在Unity中实现UDP客户端,可以使用Socket类的相关方法来发送和接收数据报。具体的实现可以参考引用中的内容。 综上所述,Unity可以通过使用Socket接口来实现TCP和UDP的通信,具体的实现可以参考引用中的内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神码编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值