日期:2014-05-16 浏览次数:20805 次
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
int main()
{
int server_sockfd = -1;
int server_len = 0;
int client_len = 0;
char buffer[512];
int result = 0;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
server_sockfd = socket(AF_INET, SOCK_DGRAM, 0);
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(9739);
server_len = sizeof(server_addr);
bind(server_sockfd, (struct sockaddr*)&server_addr, server_len);
signal(SIGCHLD, SIG_IGN);
while(1)
{
result = recvfrom(server_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&client_addr, &client_len);
if(fork() == 0)
{
buffer[0] += 'a' - 'A';
sleep(5);
sendto(server_sockfd, buffer, sizeof(buffer),0 , (struct sockaddr*)&client_addr, client_len);
printf("%c\n", buffer[0]);
}
}
close(server_sockfd);
}
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <stdio.h>
int main(int agrc, char *argv[])
{
struct sockaddr_in server_addr;
int server_len = 0;
int sockfd = -1;
int result = 0;
char c = 'A';
if(agrc > 1)
c = argv[1][0];
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(9739);
server_len = sizeof(server_addr);
sendto(sockfd, &c, sizeof(char), 0,
(struct sockaddr*)&server_addr, server_len);
recvfrom(sockfd, &c, sizeof(char), 0, 0, 0);
printf("char from server = %c\n", c);
close(sockfd);
exit(0);