iOS oc udp 包发送和接收
时间: 2023-07-29 14:14:40 浏览: 164
UDP是一种无连接的协议,因此在iOS中使用UDP发送和接收数据与TCP有所不同。以下是OC实现UDP发送和接收的基本步骤:
发送UDP包:
1. 创建UDP socket:
```
int udpSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
```
2. 设置发送地址和端口:
```
struct sockaddr_in serverAddr;
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr("目标IP地址");
serverAddr.sin_port = htons(目标端口);
```
3. 发送数据:
```
NSString *message = @"hello";
const char *msg = [message UTF8String];
sendto(udpSocket, msg, strlen(msg), 0, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
```
接收UDP包:
1. 创建UDP socket:
```
int udpSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
```
2. 设置socket端口和地址:
```
struct sockaddr_in localAddr;
memset(&localAddr, 0, sizeof(localAddr));
localAddr.sin_family = AF_INET;
localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
localAddr.sin_port = htons(本地端口);
bind(udpSocket, (struct sockaddr *)&localAddr, sizeof(localAddr));
```
3. 接收数据:
```
char buffer[1024];
struct sockaddr_in clientAddr;
socklen_t clientAddrLen = sizeof(clientAddr);
ssize_t recvLen = recvfrom(udpSocket, buffer, sizeof(buffer), 0, (struct sockaddr *)&clientAddr, &clientAddrLen);
if (recvLen > 0) {
NSString *message = [[NSString alloc] initWithBytes:buffer length:recvLen encoding:NSUTF8StringEncoding];
}
```
注意:在使用UDP协议时,需要注意数据包的大小和可靠性问题,因为UDP是无连接的,数据包可能会丢失或乱序。在实际应用中,需要根据具体情况选择合适的协议和方法。
阅读全文