Udp Server:
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define HELLO_WORLD_SERVER_PORT 6666
#define LENGTH_OF_LISTEN_QUEUE 20
#define BUFFER_SIZE 1024
typedef struct
{
int ab;
int num[1000000];
// char *s;
}Node;
int main(int argc, char **argv)
{
int step = 0;
// set socket's address information
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htons(INADDR_ANY);
server_addr.sin_port = htons(HELLO_WORLD_SERVER_PORT);
// create a stream socket
int server_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (server_socket < 0)
{
printf("Create Socket Failed!\n");
exit(1);
}
//bind
if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)))
{
printf("Server Bind Port: %d Failed!\n", HELLO_WORLD_SERVER_PORT);
exit(1);
}
while(1)
{
struct sockaddr_in client_addr;
socklen_t length = sizeof(client_addr);
Node *myNode=(Node*)malloc(sizeof(Node));
int needRecv=sizeof(Node);
char *buffer=(char*)malloc(needRecv);
int pos=0;
int len;
while(pos < needRecv)
{
len = recvfrom(server_socket, buffer+pos, BUFFER_SIZE, 0, NULL, NULL);
if (len < 0)
{
printf("Server Recieve Data Failed!\n");
break;
}
pos+=len;
}
close(server_socket);
memcpy(myNode,buffer,needRecv);
printf("recv over ab=%d num[0]=%d num[999999]=%d \n",myNode->ab,myNode->num[0],myNode->num[999999]);
free(buffer);
free(myNode);
step++;
//recvfrom非阻塞接收数据,此处使程序停留
if(step == 2)
while(1);
}
close(server_socket);
return 0;
}
Udp Client:
#include <sys/types.h>
#include <sys/socket.h> // 包含套接字函数库
#include <stdio.h>
#include <netinet/in.h> // 包含AF_INET相关结构
#include <arpa/inet.h> // 包含AF_INET相关操作的函数
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <pthread.h>
#define MYPORT 6666
#define BUFFER_SIZE 1024
typedef struct
{
int ab;
int num[1000000];
// char *s;
}Node;
int main()
{
///sockfd
int sock_cli = socket(AF_INET,SOCK_DGRAM, 0);
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(MYPORT);
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
Node *myNode=(Node*)malloc(sizeof(Node));
myNode->ab=123;
myNode->num[0]=110;
myNode->num[999999]=99;
// myNode->s="sss";
// printf("s = %s\n",myNode->s);
int needSend=sizeof(Node);
char *buffer=(char*)malloc(needSend);
memcpy(buffer,myNode,needSend);
int pos=0;
int len=0;
while(pos < needSend)
{
len=sendto(sock_cli, buffer+pos, BUFFER_SIZE, 0, (struct sockaddr *)&servaddr, sizeof(servaddr));
if(len <= 0)
{
perror("ERRPR");
break;
}
pos+=len;
}
free(buffer);
free(myNode);
close(sock_cli);
printf("Send over!!!\n");
return 0;
}