unity udp广播 android,Unity UDP广播 发送端实现

public class Glowworm : MonoBehaviour

{

private Socket socket;

private IPEndPoint iep1;

private byte[] data;

public int udpPort = 9050;

public static Glowworm instance;

public void Awake()

{

if (instance == null)

{

instance = this;

DontDestroyOnLoad(gameObject);

BroadcastIP();

}

else

{

Destroy(gameObject);

return;

}

}

public void BroadcastIP()

{

socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

iep1 = new IPEndPoint(IPAddress.Broadcast, udpPort);

data = Encoding.ASCII.GetBytes("111");

socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);

}

public void Send(string msg)

{

Debug.Log("发送消息:"+msg);

data = Encoding.ASCII.GetBytes(msg);

socket.SendTo(data, iep1);

}

private void OnApplicationQuit()

{

socket.Shutdown(SocketShutdown.Both);

socket.Close();

}

}

你可能感兴趣的:(unity,udp广播,android)