📄 server.c
字号:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <strings.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <netdb.h>
#include <net/if.h>
#include<string.h>
#include<signal.h>
#define SERVER_PORT 7051
char read_only_a_char();
int main()
{
int sfd;
struct sockaddr_in addr;
struct sockaddr_in addr_client;
socklen_t addrlen;
char ch;
char buf[1024];
int recv_len=0;
int sfd_client;
struct linger linger;
struct protoent * protocol;
if ( ( protocol = getprotobyname("tcp")) == NULL) {
fprintf(stderr, "getprotobyname fail.\n");
exit(1);
}
if( (sfd=socket(AF_INET,SOCK_STREAM,protocol->p_proto)) < 0 ) {
fprintf(stderr, ":( Create socket fail.\n");
exit(1);
} else {
fprintf(stdout, ":) Create socket successfully, sfd is : %d.\n", sfd);
}
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(SERVER_PORT);
addrlen = sizeof (struct sockaddr_in);
if ( bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) < 0 ) {
fprintf(stderr, ":( Bind socket fail.\n");
exit(1);
} else {
fprintf(stdout, ":) Bind socket successfully.\n");
}
if ( listen(sfd, 1) < 0 ) {
fprintf(stderr, ":( Listen socket fail.\n");
exit(1);
} else {
fprintf(stdout, ":) Listen socket successfully.\n");
}
while(1) {
fprintf(stdout,":> Do you want to accept connect?(y/n)\n");
ch = read_only_a_char();
if(ch == 'y') {
break;
}
}
if ( (sfd_client=accept(sfd, (struct sockaddr *)&addr_client, &addrlen)) < 0 ) {
fprintf(stderr, ":( Accept client fail.\n");
exit(1);
} else {
fprintf(stdout, ":) Accept client successfully.\n");
}
memset(&linger,0,sizeof(linger));
linger.l_onoff = 0;
setsockopt(sfd_client,SOL_SOCKET,SO_LINGER,(const char*)&linger,sizeof(linger));
while(1) {
fprintf(stdout, ":> Do you want to recv data or quit?(r/q)\n");
ch = read_only_a_char();
if(ch == 'q') {
break;
} else if (ch == 'r') {
if ( (recv_len=recv(sfd_client, buf, 1024, 0)) < 0 ) {
fprintf(stderr, ":( Recv data fail.\n");
exit(1);
} else {
buf[recv_len] = 0;
fprintf(stdout, ":) Recv data : %d-%s successfully.\n",recv_len,buf);
}
}
}
while(1) {
fprintf(stdout, ":> Do you want to close client_sfd?(y/n)\n");
ch = read_only_a_char();
if(ch == 'y') {
break;
}
}
close (sfd_client);
while(1) {
fprintf(stdout, ":> Do you want to close server_sfd and kill me?(y/n)\n");
ch = read_only_a_char();
if(ch == 'y') {
break;
}
}
close (sfd);
printf(":) bye-bye.\n");
return 0;
}
char read_only_a_char()
{
char ch,ch_tmp;
if ( scanf("%c", &ch) != EOF ) {
while ( (ch_tmp=getchar()) != '\n' && ch_tmp != EOF );
}
return ch;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -