UPD服务端向客户端发送数据
代码展示
下面展示一些 内联代码片
。
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class ServerUdp : MonoBehaviour
{
private Socket _socket;
private IPEndPoint _endPoint;
private byte[] _data;
public int _udpPort = 9050;
private bool isReceive = false;
public string _currentSendId;
public string _isModelOrScenes;
/// <summary>
/// 当前推送的item
/// </summary>
public GameObject _curSelectObject = null;
public void Awake()
{
DontDestroyOnLoad(gameObject);
BroadcastIP();
_currentSendId = null;
_isModelOrScenes = null;
}
public void Send(string msg)
{
//Debug.Log("发送消息id:"+ _currentSendId +" ,msg = " + msg);
_data = Encoding.ASCII.GetBytes(msg);
_socket.SendTo(_data, _endPoint);
isReceive = true;
}
private void OnApplicationQuit()
{
Debug.Log("关闭socket");
if (isReceive)
{
_socket.Shutdown(SocketShutdown.Both);
}
_socket.Close();
}
public void BroadcastIP()
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_endPoint = new IPEndPoint(IPAddress.Broadcast, _udpPort);
_data = Encoding.ASCII.GetBytes("hello");
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
}