您的位置:首页 > 其它

[国嵌攻略][093][并发服务器设计]

2016-03-02 09:45 246 查看
server.c

#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#define SERVER_PORT 3333

void main(){
//创建标识
int serverfd;

serverfd = socket(AF_INET, SOCK_STREAM, 0);   //建立TCP连接

//绑定地址
struct sockaddr_in serverAddr;

serverAddr.sin_family = AF_INET;                   //设置协议
serverAddr.sin_port = htons(SERVER_PORT);          //设置端口
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);    //设置地址
bzero(serverAddr.sin_zero, 8);                     //设置为零

bind(serverfd, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr));

//监听端口
listen(serverfd, 10);

while(1){
//等待连接
socklen_t clientAddrLen;
struct sockaddr_in clientAddr;
int clientfd;

clientAddrLen = sizeof(struct sockaddr);
clientfd = accept(serverfd, (struct sockaddr *)&clientAddr, &clientAddrLen);

//创建进程
int pid;

pid = fork();
if(pid == 0){
//接收数据
char buffer[2048];

recv(clientfd, buffer, sizeof(buffer), 0);

//显示数据
char *clientIPAddr;

clientIPAddr = (char *)inet_ntoa(clientAddr.sin_addr.s_addr);
printf("server recvice from %s:\n%s", clientIPAddr, buffer);

//关闭连接
close(clientfd);
close(serverfd);

//结束进程
exit(0);
}

//关闭连接
close(clientfd);
}

//关闭连接
close(serverfd);
}


client.c

#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <stdio.h>

#define SERVER_PORT 3333

int main(int argc, char **argv){
//参数检查
if(argc != 2){
printf("Usage:\n\t./client <ip address>\n");
return -1;
}

//创建标识
int clientfd;

clientfd = socket(AF_INET, SOCK_STREAM, 0);   //建立TCP连接

//建立连接
struct sockaddr_in serverAddr;

serverAddr.sin_family = AF_INET;                   //设置协议
serverAddr.sin_port = htons(SERVER_PORT);          //设置端口
serverAddr.sin_addr.s_addr = inet_addr(argv[1]);   //设置地址
bzero(serverAddr.sin_zero, 8);                     //设置为零

connect(clientfd, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr));

//输入数据
char buffer[2048];

printf("client send to %s:\n", argv[1]);
fgets(buffer, sizeof(buffer), stdin);

//发送数据
send(clientfd, buffer, sizeof(buffer), 0);

//关闭连接
close(clientfd);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: