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();
}
}