?? test14_1.txt
字號(hào):
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>
#include <arpa/inet.h>
//#include "safecalls.h"
#define PROTOCOL "tcp"
#define SERVICE 7797
#define WELCOME "You have connected to the counting server. Welcome! \n"
int readnlstring(int socket,char *buf,int maxlen);
int read_buffer(int fd,void *buf,int count);
int readdelimstring(int socket,char *buf,int maxlen,char delim);
int main(void){
int listensock,workersock;
struct protoent *protocol;
struct sockaddr_in socketaddr;
char buffer[1024];
char size[100];
int addlen;
int trueval=1;
/* 初始化套接字地址結(jié)構(gòu)*/
bzero((char *)&socketaddr,sizeof(socketaddr));
socketaddr.sin_family=AF_INET;
socketaddr.sin_addr.s_addr=INADDR_ANY;
socketaddr.sin_port=htons(SERVICE);
protocol=getprotobyname(PROTOCOL);
if(!protocol){
HandleError(0, "getprotobyname", "protocol resolution failed");
}
/*創(chuàng)建主控和監(jiān)聽套接字*/
listensock=socket(PF_INET,SOCK_STREAM,protocol->p_proto);
if(listensock<0){
HandleError(errno, "socket", "couldn’t create socket");
}
/*將套接字綁定到服務(wù)器的某個(gè)端口*/
if(bind(listensock,&socketaddr,sizeof(socketaddr))<0){
HandleError(errno, "bind", "couldn’t bind to port %d", SERVICE);
}
/*告訴系統(tǒng)監(jiān)聽連接*/
setsockopt(listensock,SOL_SOCKET,SO_REUSEADDR,&trueval,sizeof(trueval));
if(listen(listensock,0)<0){
HandleError(errno, "listen", "couldn’t listen on port %d",SERVICE);
}
printf("Listening for a connection…\n");
workersock=accept(listensock,&socketaddr,&addlen);
if(workersock<0){
HandleError(errno, "accept", "couldn’t open worker socket");
}
printf("Received connection from a client at");
printf("%s port %d\n",inet_ntoa(socketaddr.sin_addr),
ntohs(socketaddr.sin_port));
write_buffer(workersock,WELCOME,strlen(WELCOME));
while(readnlstring(workersock,buffer,sizeof(buffer))>=0){
sprintf(size,"Size:%d\n",strlen(buffer)-1);
write_buffer(workersock,size,strlen(size));
if(strncmp(buffer, "exit",4)==0)
break;
}
printf("Shutting down.\n");
safeclose(workersock);
safeclose(listensock);
return 0;
}
int write_buffer(int fd,const void *buf,int count){
const void *pts=buf;
int status=0,n;
if(count<0)
return(-1);
while(status!=count){
n=safewrite(fd,pts+status,count-status);
if(n<0)
return(n);
status+=n;
}
return(status);
}
int read_buffer(int fd,void *buf,int count){
void *pts=buf;
int status=0,n;
if(count<0)
return(-1);
while(status!=count){
n=saferead(fd,pts+status,count-status);
if(n<1)
return n;
status+=n;
}
return(status);
}
int readnlstring(int socket,char *buf,int maxlen){
return readdelimstring(socket,buf,maxlen, '\n');
}
int readdelimstring(int socket,char *buf,int maxlen,char delim){
int status;
int count=0;
while(count<maxlen-1){
if((status=read_buffer(socket,buf+count,1))<1){
return -1;
}
if(buf[count]==delim){
buf[count]=0;
return 0;
}
count++;
}
buf[count]=0;
return 0;
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -