c# 使用udp协议接收消息
@【】
两个例子
例一:
引用命名空间
using System.Net;
using System.Net.Sockets;
定义
private UdpClient Reveive;
IPAddress localIP = IPAddress.Parse(GetLocalIpv4()[0]);//获取本机ip地址,也可以自己手动填写
IPEndPoint localIPEndPoint = new IPEndPoint(localIP, 8888);//设置ip和端口
Reveive = new UdpClient(localIPEndPoint);
//启动接收线程
Thread threadReceive = new Thread(ReceiveMessages);//线程回调函数为ReceiveMessages
threadReceive.IsBackground = true;
threadReceive.Start();//开启
//获取本机IP
private string[] GetLocalIpv4()//获取本机ip
{
//事先不知道ip的个数,数组长度未知,因此用StringCollection储存
IPAddress[] localIPs;
localIPs = Dns.GetHostAddresses(Dns.GetHostName());
StringCollection IpCollection = new StringCollection();
foreach (IPAddress ip in localIPs)
{
//根据AddressFamily判断是否为ipv4,如果是InterNetWorkV6则为ipv6
if (ip.AddressFamily == AddressFamily.InterNetwork)
IpCollection.Add(ip.ToString());
}
string[] IpArray = new string[IpCollection.Count];
IpCollection.CopyTo(IpArray, 0);
return IpArray;
}
//线程回调函数
private void ReceiveMessages()//线程回调函数
{
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
try
{
byte[] receiveBytes = Reveive.Receive(ref remoteIPEndPoint);
string message = System.Text.Encoding.ASCII.GetString(receiveBytes, 0, receiveBytes.Length);
string[] date = message.Split('$');
Command = date[0];
switch (Command)
{
case "message1":
//收到消息:message1
break;
case "message2":
//收到消息:message2
break;
default:
break;
}
}
catch (Exception e)
{
break;
}
}
}
试试能不能收到消息吧
脚本2:
using System.Collections;
//引入库
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class UDPClient : MonoBehaviour
{
//以下默认都是私有的成员
Socket socket; //目标socket
EndPoint clientEnd; //客户端
IPEndPoint ipEnd; //侦听端口
string recvStr; //接收的字符串
string sendStr; //发送的字符串
byte[] recvData = new byte[1024]; //接收的数据,必须为字节
byte[] sendData = new byte[1024]; //发送的数据,必须为字节
int recvLen; //接收的数据长度
Thread connectThread; //连接线程
private void Start()
{
InitSocket();
}
void InitSocket()
{
//定义侦听端口,侦听任何IP
ipEnd = new IPEndPoint(IPAddress.Any, 1232);
//定义套接字类型,在主线程中定义
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//服务端需要绑定ip
socket.Bind(ipEnd);
//定义客户端
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
clientEnd = (EndPoint)sender;
print("waiting for UDP dgram");
//开启一个线程连接,必须的,否则主线程卡死
connectThread = new Thread(new ThreadStart(SocketReceive));
connectThread.Start();
print("开始线程!");
}
void SocketSend(string sendStr)
{
print(sendStr);
}
//服务器接收
void SocketReceive()
{
//进入接收循环
while (true)
{
//对data清零
recvData = new byte[1024];
//获取客户端,获取客户端数据,用引用给客户端赋值
recvLen = socket.ReceiveFrom(recvData, ref clientEnd);
print("message from: " + clientEnd.ToString()); //打印客户端信息
//输出接收到的数据
recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);
print("我是服务器,接收到客户端的数据" + recvStr);
//将接收到的数据经过处理再发送出去
sendStr = "From Server: " + recvStr;
SocketSend(sendStr);
print("接收!");
}
}
//连接关闭
void SocketQuit()
{
//关闭线程
if (connectThread != null)
{
connectThread.Interrupt();
connectThread.Abort();
}
//最后关闭socket
if (socket != null)
socket.Close();
print("disconnect");
}
void OnDestroy()
{
SocketQuit();
}
}
小结:socket通信中的UDP、TCP还有串口通信的使用方法都大致相似,本文中只讲了应用,具体详细的解析后边我会继续完善,文中若有不足或错误请直接指出,欢迎评论交流。
学习入口: