1.修改main.c文件:
添加Server,StartServer,Client三个函数,将下列代码直接添加到main.c中:
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<netdb.h>
#include<errno.h>
#define PORT 8888
#define MAX_MSG_SIZE 1024
int Server(void)
{
int sockfd, addrlen, n;
struct sockaddr_in addr;
char msg[10];
char str[]={"hi"};
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
fprintf(stderr, "socket failed\n");
exit(EXIT_FAILURE);
}
addrlen = sizeof(struct sockaddr_in);
bzero(&addr, addrlen);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(PORT);
if (bind(sockfd, (struct sockaddr*)(&addr), addrlen) < 0)
{
fprintf(stderr, "bind fail\n");
exit(EXIT_FAILURE);
}
n = recvfrom(sockfd, msg, sizeof(msg), 0, (struct sockaddr *)(&addr), &addrlen);
fprintf(stdout, "Recevie message from client is %s\n", msg);
printf("Server endpoint input message %s\n", str);
sendto(sockfd, str, n, 0,(struct sockaddr *)(&addr), addrlen);
close(sockfd);
return 0;
}
int StartServer(int argc, char *argv[])
{
int pid;
/* fork another process */
pid = fork();
if (pid < 0)
{
/* error occurred */
fprintf(stderr, "Fork Failed!");
exit(-1);
}
else if (pid == 0)
{
/* child process */
Server();
printf("Reply hi TCP Service Started!\n");
}
else
{
/* parent process */
printf("Please input udpC...\n");
}
}
int Client()
{
int sockfd, addrlen, n;
char buffer[]={"hello"};
struct sockaddr_in addr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
fprintf(stderr, "socket falied\n");
exit(EXIT_FAILURE);
}
addrlen = sizeof(struct sockaddr_in);
bzero(&addr, addrlen);
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)(&addr), addrlen);
printf("client send msg is %s\n", buffer);
n = recvfrom(sockfd, buffer, 10, 0, (struct sockaddr *)(&addr), &addrlen);
fprintf(stdout, "clinet Receive message from server is %s\n", buffer);
close(sockfd);
return 0;
}
2.在main()中添加启动相应函数的命令:
MenuConfig("udpS", "server", StartServer);
MenuConfig("udpC", "client", Client);
到这一步main.c修改完成。
3.启动MENUOS环境:
使用help命令查看添加的命令,可以看到已经将udpS和udpC命令添加进去了:
首先输入命令udpS启动服务器:
然后输入udpC启动客户端完成通信:
到这里全部完成。
代码参考:https://blog.csdn.net/u011068702/article/details/56680752