123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- using System;
- using System.Collections;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using UnityEngine;
- public class UdpServer : MonoBehaviour
- {
- public static float resR;
- int serverPort = 8085;
- int broadcastPort = 8085;
- private UdpClient udpServer;
- private UdpClient udpBroadcastClient;
- private void Start()
- {
- udpServer = new UdpClient(serverPort);
- udpServer.BeginReceive(ReceiveCallback, null);
- udpBroadcastClient = new UdpClient();
- udpBroadcastClient.EnableBroadcast = true;
- Debug.Log("IPAddress.Any+=="+ IPAddress.Any );
- //StartCoroutine("sendudp");
- }
- private void ReceiveCallback(IAsyncResult result)
- {
- string receivedMessage = "";
- try
- {
- IPEndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, serverPort);
- byte[] receivedBytes = udpServer.EndReceive(result, ref clientEndPoint);
- receivedMessage = Encoding.ASCII.GetString(receivedBytes);
- }
- catch (Exception e)
- {
- Debug.LogError("Error receiving UDP message: " + e.Message);
- }
- try
- {
- string[] q1 = receivedMessage.Split(new char[2] { 'R', 'T' });
- Debug.Log("收到来自客户端的消息: " + receivedMessage + " q" + q1[1]);
- resR = float.Parse(q1[1]);
- }
- catch (Exception e)
- {
- Debug.LogError("Error receiving UDP message: " + e.Message);
- }
- // 继续接收下一个消息
- try
- {
- udpServer.BeginReceive(ReceiveCallback, null);
- }
- catch (Exception e)
- {
- Debug.LogError("Error receiving UDP message: " + e.Message);
- }
- }
- public void SendBroadcastMessage(string message)
- {
- Debug.Log("IPAddress.Broadcast===>"+ IPAddress.Broadcast);
- IPEndPoint broadcastEndPoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), broadcastPort);
- byte[] messageBytes = Encoding.ASCII.GetBytes(message);
- udpBroadcastClient.Send(messageBytes, messageBytes.Length, broadcastEndPoint);
- }
- private void OnDestroy()
- {
- if (udpServer != null)
- {
- udpServer.Close();
- }
- if (udpBroadcastClient != null)
- {
- udpBroadcastClient.Close();
- }
- }
- IEnumerator sendudp()
- {
- yield return null;
- while (true)
- {
- Debug.Log("发送hello");
- SendBroadcastMessage("hello client!");
- yield return null;
- }
- }
- private void Update()
- {
- if (Input.GetKeyDown(KeyCode.K))
- {
- Debug.Log("发送");
- SendBroadcastMessage("hello client!");
- }
- }
- }
|