tcpserver
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
/* TCP Tinh cac bieu thuc (server)*/
void error(char *message)
{
printf("%s
",message);
exit(1);
}
int UCLN(int a, int b);
int main()
{
int sockfd, newsockfd, clilen;
int portno=12345;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
//-----------------------------
//printf("Day la Server!
");
//------------------------------
//Step 1: Create Socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("Loi mo Socket");
//------------------------------
//Step 2: Bind to port
serv_addr.sin_family = AF_INET;
//serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_addr.s_addr =inet_addr("127.0.0.1");//sua cho nay
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR on binding");
//-----------------------------
//Step 3: Listen
listen(sockfd,5);
//-----------------------------
//Step 4: Waiting for connection request
printf("Cho Client...");
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("Loi Chap Nhan");
printf("Da ket noi
");
//----------------------------
//Step 5: Begin sending/receiving data
printf("Bai5: TCP Tinh cac bieu thuc
");
printf("Day la server
");
int a, b,kq;
recv(newsockfd, &a, sizeof(a),0);
recv(newsockfd, &b, sizeof(b),0);
//Goi cac ham tinh toan
switch(a)
{
case 1:
kq=ham1(b);
break;
case 2:
kq=ham2(b);
break;
case 3:
kq=ham3(b);
break;
case 4:
kq=ham4(b);
break;
case 5:
kq=ham5(b);
break;
case 6:
kq=ham6(b);
break;
case 7:
kq=ham7(b);
break;
default:
{a =0;}
}
//Gui ket qua cho Client
send(newsockfd,(char*)&kq,100,0);
//------------------------------
//Step 6: Close socket
close(sockfd);
close(newsockfd);
return 0;
}
//Ham1 Tong 1+3+5+7+...+(2n+1)
int ham1(int n){
int s=0;
int i;
for(i=1; i<=(2*n+1); i++)
if(i%2==1)
s=s+i;
return s;
}
//Ham2 Tong 1*2 + 2*3+...+n*(n+1)
int ham2(int n){
int s=0;
int i;
for(i=1; i<=n; i++)
s=s+i*(i+1);
return s;
}
//Ham3 Bieu thuc 1-2+3-4+..+(2n+1)
int ham3(int n)
{
int s=0;
int i;
for(i=1; i<=(2*n+1); i++)
if(i%2==1)
s=s+i;
else
s=s-i;
return s;
}
//Ham4 Bieu thuc 1^2+2^2+3^2+4^2+..+n^2 (n>=0)
int ham4(int n)
{
int s=0;
int i;
for(i=1; i<=n; i++)
s=s+i*i;
return s;
}
//Ham5 Bieu thuc 1^3+2^3+3^3+4^3+..+n^3 (n>=0)
int ham5(int n)
{
int s=0;
int i;
for(i=1; i<=n; i++)
s=s+i*i*i;
return s;
}
//Ham6 Bieu thuc 1^2+3^2+5^2+..+(2n+1)^2 (n>=0)
int ham6(int n)
{
int s=0;
int i;
for(i=1; i<=(2*n+1); i++)
if(i%2==1)
s=s+i*i;
return s;
}
//Ham7 Bieu thuc 2^2+4^2+6^2+..+(2n)^2 (n>=0)
int ham7(int n)
{
int s=0;
int i;
for(i=2; i<=(2*n); i++)
if(i%2==0)
s=s+i*i;
return s;
}
Bạn đang đọc truyện trên: AzTruyen.Top