/*
* Filename : server.c
* copyright
: 信息交换服务器。
* Function
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <ctype.h>
#define BUFSIZE 16384
char buf[3][BUFSIZE]; //收发数据缓冲区
int server_socket; //服务器套接口
int port = 8088; //服务端口号
struct sockaddr_in server_in; //服务器网络地址
int client_socket[3]; //客户端套接口
socklen_t client_size; //客户端网络地址长度
struct sockaddr_in client_in; //客户端网络地址
int main(int argc,char *argv[])
{
int x,y,i,len[3];
//申请 TCP/IP 协议的套接口
if((server_socket = socket(AF_INET,SOCK_STREAM,0)) == -1 ){
perror("call to socket");
exit(1);
}
//初始化 IP 地址
bzero(&server_in,sizeof(server_in));//清 0
server_in.sin_family = AF_INET;
server_in.sin_addr.s_addr = INADDR_ANY;
server_in.sin_port = htons(port);
//套接口捆定 IP 地址
if(bind(server_socket,(struct sockaddr *)&server_in,sizeof(server_in)) == -1){
perror("call to bind");
exit(1);
}
//监听网络请求
if(listen(server_socket,200) == -1){
perror("call to listen");
exit(1);
}
//循环等待接收信息和处理信息
printf("Accepting connections ...\n");
while(1){
bzero(buf[0],sizeof(buf[0]));
bzero(buf[1],sizeof(buf[1]));
bzero(buf[2],sizeof(buf[2]));
printf("Please input x:....\n");
scanf("%s",buf[0]);
printf("Please input y:....\n");
scanf("%s",buf[1]);
len[0] = strlen(buf[0]);
len[1] = strlen(buf[1]);
//接收第一客户请求
if((client_socket[0] = accept(server_socket,(struct sockaddr
*)&client_in,&client_size)) == -1){
perror("call to accept 1 ");
exit(1);
}
//接收第二客户请求
if((client_socket[1] = accept(server_socket,(struct sockaddr
*)&client_in,&client_size)) == -1 ){
perror("call to accept 2 ");
exit(1);
}
if((client_socket[2] = accept(server_socket,(struct sockaddr
*)&client_in,&client_size)) == -1 ){
perror("call to accept 2 ");
exit(1);
}
//都转换为大写
//把第二客户发来的数据发给第一客户
if(send(client_socket[0],buf[0],len[0],0) == -1){
perror("call to send 1");
exit(1);
}
printf("send to client1: %s\n",buf[0]);
//把第一客户发来的数据发给第二客户
if(send(client_socket[1],buf[1],len[1],0) == -1){
perror("call to send 1");
exit(1);
}
//获取第一客户发送的数据
if(recv(client_socket[0],buf[0],BUFSIZE,00) == -1){
perror("call to recv 1");
exit(1);
}
len[0] = strlen(buf[0]);
printf("received from client1: %s\n",buf[0]);
//获取第二客户发送的数据
if(recv(client_socket[1],buf[1],BUFSIZE,0) == -1){
perror("call to recvv 2");
exit(1);
}
printf("received from client2: %s\n",buf[1]);
len[1] = strlen(buf[1]);
printf("len[0],%d\n",len[0]);
if(send(client_socket[2],buf[0],len[0],0) == -1){
perror("call to send 3");
exit(1);
}
printf("send to client3: %s\n",buf[0]);
if(send(client_socket[2],buf[1],len[1],0) == -1){
perror("call to send 3");
exit(1);
}
printf("send to client3: %s\n",buf[1]);
if(recv(client_socket[2],buf[2],BUFSIZE,0) == -1){
perror("call to recvv 2");
exit(1);
}
printf("received from client3: %s\n",buf[2]);
printf("result:%s\n",buf[2]);
//断开与客户的连接
close(client_socket[0]);
close(client_socket[1]);
close(client_socket[2]);
}
}