客户端代码
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string.h>
#include <time.h>
#define MAX 1024
int main ( int argc, char ** argv)
{
printf("Check point 1\n");
if (argc != 2)
{
printf("Error!! Provide a correct port\n");
exit (0);
}
unsigned char buff[MAX];
int port = atoi(argv[1]);
int sockfd;
struct sockaddr_in myAddr, Addr;
unsigned char temp[MAX];
char buffer [MAX];
socklen_t addr_size;
addr_size = sizeof(Addr);
//_os_getime();
printf("Check point 2\n");
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0))< 0)
{
printf ( "%d", sockfd);
perror("socket failed");
exit(EXIT_FAILURE);
}
memset(&myAddr,'\0', sizeof(myAddr));
myAddr.sin_family = AF_INET;
myAddr.sin_port = htons(port);
myAddr.sin_addr.s_addr =inet_addr("127.0.0.1");
printf ("Check point 3");
strcpy(buff, "ABCDE\n");
if((sendto(sockfd, buff, MAX, 0 , (struct sockaddr*) &myAddr, sizeof(myAddr)))<0)
{
perror("Sending failed--");
exit(EXIT_FAILURE);
}
printf ("Check point 4");
if((recvfrom(sockfd, buffer, sizeof(buffer), 0 , (struct sockaddr*) &Addr, &addr_size))<0)
{
perror("Receiving failed");
exit(EXIT_FAILURE);
}
printf ( "%s", buff);
close(sockfd);
return 0;
}
服务器代码
#include <stdio.h>
#include <stdlib.h>
/*
#include <modes.h>
#include <events.h>
#include <process.h>
#include <alarm.h>
#include <signal.h>
#include <module.h>
#include <sg_codes.h>
#include <sgstat.h>
#include <sys/types.h>
*/
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string.h>
#include <time.h>
#define MAX 1024
int main (int argc, char ** argv)
{
if (argc != 2)
{
printf("Error!! Provide a correct port\n");
exit (0);
}
int port = atoi(argv[1]);
char buff[MAX];
char buffer [MAX];
int sockfd, clientfd;
struct sockaddr_in myAddr, Addr;
socklen_t addr_size;
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0))< 0)
{
printf ( "%d", sockfd);
perror("socket failed");
exit(EXIT_FAILURE);
}
memset(&myAddr,'\0', sizeof(myAddr));
myAddr.sin_family = AF_INET;
myAddr.sin_port = htons(port);
myAddr.sin_addr.s_addr =inet_addr("127.0.0.1");
if ((bind (sockfd, (struct sockaddr*) &myAddr, sizeof(myAddr)))<0)
{
perror("Binding failed");
exit(EXIT_FAILURE);
}
addr_size = sizeof(Addr);
int recv = recvfrom(sockfd, buff, MAX, 0 , (struct sockaddr*) &Addr, &addr_size);
printf ( "%s", buff);
strcpy(buffer, "EFGH");
if((sendto(sockfd, buffer, MAX, 0 , (struct sockaddr*) &myAddr, sizeof(myAddr)))<0)
{
perror("Sending failed");
exit(EXIT_FAILURE);
}
close(sockfd);
return 0;
}
这是关于套接字编程的简单代码 当我启动服务器然后启动客户端时,消息ABCDE被发送到服务器并且消息将在服务器上打印并且服务器将被终止。 但是在客户端,代码不会被终止并且只在检查点2之前执行。我不明白为什么检查点3没有被打印,即使下一行正在工作。 当然,从服务器到客户端的消息也没有打印出来