当前位置: 技术问答>linux和unix
小妹高分求助
来源: 互联网 发布时间:2016-03-22
本文导语: 用socket 编写一个网络程序,一个TCP server 能同时接受多个client的请求,server有一个计数器,counter, 每当一个client和server连接,server的counter就累加1,然后把当前的计数器总数返回给client,client打印出该数。 ...
用socket 编写一个网络程序,一个TCP server 能同时接受多个client的请求,server有一个计数器,counter, 每当一个client和server连接,server的counter就累加1,然后把当前的计数器总数返回给client,client打印出该数。
谢谢!
|
//server.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVPORT 2234
#define BACKLOG 10
int main( int argc , char argv[])
{
printf("hello linuxn");
int sockfd,client_fd;
struct sockaddr_in my_addr;
struct sockaddr_in remote_addr;
char buf[32];
int count=0;
printf("socket ready creating!n");
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
printf("creat socket error!n");
exit(1);}
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr = htons(INADDR_ANY);
printf("socket creat ok!!!n");
memset(&(my_addr.sin_zero),0,8);
int BIND=bind(sockfd,(struct sockaddr*)&my_addr,sizeof(struct sockaddr));
if(BIND==-1)
{
printf("bind error!!!n");
exit(1);
}
printf("bind ok!!!n");
if(listen(sockfd,BACKLOG)==-1)
{
printf("listen error!!!n");
exit(1);
}
printf("listen ok!!!!n");
while(1) {
socklen_t sin_size = sizeof(struct sockaddr_in);
if ((client_fd = accept(sockfd, (struct sockaddr *) &remote_addr, &sin_size)) == -1) {
perror( "accept error");
continue;
}
printf( "received a connection from %sn", inet_ntoa(remote_addr.sin_addr));
count++;
memset(buf,0,sizeof(buf));
sprintf(buf,"%d",count);
//if (!fork()) {
if (send(client_fd, buf,10, 0) == -1)
perror( "sende rror!");
close(client_fd);
//exit(0);
//}
//close(client_fd);
}
}
//client.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MYPORT 2234
#define BACKLOG 10
int main(int argc, char **argv)
{
int sockfd;
char buffer[1024];
struct sockaddr_in server_addr;
struct hostent *host;
int portnumber,nbytes;
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
printf("socket errorn");
return -1 ;
}
bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(MYPORT);
server_addr.sin_addr.s_addr= inet_addr("192.168.0.88") ;
int nsock;
nsock=connect(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr));
if(nsock==-1)
{
perror("connect errorn");
return -1;
}
if((nbytes=read(sockfd,buffer,10))==-1)
{
printf("read errorn");
return -1 ;
}
buffer[nbytes]='';
printf("I have received:%sn",buffer);
/* bzero(buffer,sizeof(buffer));
scanf("%s",buffer);
int len, bytes_sent;
bytes_sent = write(sockfd, buffer,strlen(buffer));
printf("okn");*/
close(sockfd);
}
|
不大了解,帮顶了。