USCLNserver
#include <stdio.h>
#include <stdlib.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("192.168.1.2");//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,c,kq;
recv(newsockfd, &a, sizeof(a),0);
recv(newsockfd, &b, sizeof(b),0);
recv(newsockfd, &c, sizeof(c),0);
printf("Nhap gia tri tu client: (%d,%d)
",a,b);
//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,c);
break;
case 5:
kq=ham5(b,c);
break;
default:
{}
}
//Gui ket qua cho Client
send(newsockfd,(char*)&kq,100,0);
printf("Tinh ket qua thanh cong...
");
//------------------------------
//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;
//s=n+1;
for(i=1; i<=n; i++)
s=s+((2*i-1)-(2*i));
return s;
}
int ham4(int n,int m)
{
while(n!=m)
if(n>m)
n=n-m;
else
m=m-n;
return n;
}
int ham5(int n,int m)
{
int i;
if (n>m)
i = n;
else
i=m;
for(;;i++)
if(i % n == 0 && i % m == 0)
return i;
}
Bạn đang đọc truyện trên: AzTruyen.Top