📄 p12-28.c
字号:
#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <netdb.h>#include <stdio.h>#include <sys/time.h>#include "err_exit.h"#define MAXMSG 512int main(int argc, char **argv) { int sock,n; struct sockaddr_in name; struct hostent *hp; char sndmsg[MAXMSG],rcvmsg[MAXMSG]; struct timeval timev; /* 检查参数的合法性 */ if (argc < 3) { fprintf(stderr, "Usage: a.out <hostname> <port>\n"); exit(1); } if ((sock = socket(AF_INET, SOCK_DGRAM, 0))< 0) err_exit("opening datagram socket"); /* 形成发送目的地套接字缺省地址 */ init_sockaddr(&name, argv[1], argv[2]); /* 设置套接字接收超时选项 */ timev.tv_sec = 5; timev.tv_usec = 0; setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timev, sizeof(timev)); while(fgets(sndmsg,MAXMSG,stdin) != NULL){ /* 发送从终端读入的消息 */ if (sendto(sock, sndmsg, sizeof(sndmsg), 0, &name, sizeof(name)) < 0) perror("(client) sending error"); /* 接收并显示服务返回的回答,若超时或出错,终止执行 */ if ((n = read(sock,rcvmsg, MAXMSG, 0, NULL, NULL)) < 0){ if (errno == EWOULDBLOCK) fprintf(stderr,"socket timeout\n"); else perror("(client) receive error "); close(sock); exit(1); } rcvmsg[n] = 0; printf("client received message: %s",rcvmsg); } close(sock); exit(0); }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -