在unity里面 怎么得到接收udp消息的消息头
初始化
ipEnd = new IPEndPoint(IPAddress.Parse(ipAddress), ConnectPort);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(ipEnd);
//定义客户端
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
clientEnd = (EndPoint)sender;
//开启一个线程连接
connectThread = new Thread(new ThreadStart(SocketReceive));
connectThread.Start();
接收 recvData = new byte[81920];
recvLen = socket.ReceiveFrom(recvData, ref clientEnd);
recvStr = Encoding.UTF8.GetString(recvData, 0, recvLen);
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using System;
public class UDPClient2Client : MonoBehaviour
{
public static UDPClient2Client Instance = null;
private UdpClient client;
private Thread thread = null;
private IPEndPoint remotePoint;
public string ip="127.0.0.1";
private int port = 9090;
public Action<string> receiveMsg = null;
private string receiveString = null; void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
// Use this for initialization
void Start()
{
// ip = IPManager.ipAddress;
remotePoint = new IPEndPoint(IPAddress.Any, 0);
thread = new Thread(ReceiveMsg);
thread.Start();
}
//接受消息
void ReceiveMsg()
{
while (true)
{
client = new UdpClient(port);
byte[] receiveData = client.Receive(ref remotePoint);//接收数据
receiveString = Encoding.UTF8.GetString(receiveData);
client.Close();
}
}
//发送消息
void SendMsg(IPAddress ip, string _msg)
{
IPEndPoint remotePoint = new IPEndPoint(ip, port);//实例化一个远程端点
if (_msg != null)
{
byte[] sendData = Encoding.Default.GetBytes(_msg);
UdpClient client = new UdpClient();
client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点
client.Close();//关闭连接
}
}
// Update is called once per frame
void Update()
{
if (!string.IsNullOrEmpty(receiveString))
{
//消息处理
if (receiveMsg != null && remotePoint.Address.ToString() != ip)
{
Debug.Log(remotePoint.Address + ":" + remotePoint.Port + " ---> " + receiveString);
receiveMsg.Invoke(receiveString);
receiveString = null;
}
}
}
void OnDestroy()
{
SocketQuit();
}
void SocketQuit()
{
thread.Abort();
thread.Interrupt();
client.Close();
}
void OnApplicationQuit()
{
SocketQuit();
}
}
接受消息添加委托
void Start()
{
UDPClient2Client.Instance.receiveMsg = Rstring;
}
void Rstring(string str) {
Debug.Log(str);
}
其实自己写SOCKET底层很难的,不是大牛根本做不好。我选择用国人写好的开源引擎HP-OSCKET,什么TCP、UDP都可以轻松搞定。。。
消息头??你问我们消息头,我们可不知道啥是消息头的
比如:基于udp的rstp协议头是这样的“udp去8个字节的头为rtp数据,rtp去12个字节的头为流数据,udp 8个字节分别为端口号两个,长度一个。端口号长度为2个字节,有效范围是0到65536。”
比如:基于udp的ssdp发现协议的协议头长成这样
M-SEARCH * HTTP/1.1
HOST: 239.255.255.250:1900
MAN: "ssdp:discover"
MX: 5
ST: ssdp:all
所以,啥叫消息头我们不知道。
byte[] receiveData = client.Receive(ref remotePoint);
我们只能知道对方发过来的数据是他,而所谓的消息头是你们俩自己定的,我们不知道的。如果你说我们是rstp协议,那我告诉你消息头是前8位
如果你说我们是ssdp发现协议,那我告诉你消息头是你收到的这串byte[] 出现的一个“2次回车换行”前的所有byte[]