Centos 64下实现socket通信
来源:程序员人生 发布时间:2015-04-21 09:09:11 阅读次数:4043次
源码:
/* File Name: server.c */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h> //Ineternet address family
#include<arpa/inet.h>
#define DEFAULT_PORT 8000
#define MAXLINE 4096
int main(int argc, char** argv)
{
int socket_fd, connect_fd;
struct sockaddr_in servaddr;
char buff[4096];
int n;
//初始化Socket
if( (socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == ⑴ ){
printf("create socket error: %s(errno: %d)
",strerror(errno),errno);
exit(0);
}
//初始化
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);//IP地址设置成INADDR_ANY,让系统自动获得本机的IP地址。
servaddr.sin_port = htons(DEFAULT_PORT);//设置的端口为DEFAULT_PORT
//将本地地址绑定到所创建的套接字上
if( bind(socket_fd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == ⑴){
printf("bind socket error: %s(errno: %d)
",strerror(errno),errno);
exit(0);
}
//开始监听是不是有客户端连接
if( listen(socket_fd, 10) == ⑴){
printf("listen socket error: %s(errno: %d)
",strerror(errno),errno);
exit(0);
}
printf("======waiting for client's request======
");
while(1){
struct sockaddr_in cilent_addr; //客户端socket地址结构
socklen_t length = sizeof(cilent_addr);
//阻塞直到有客户端连接,不然多浪费CPU资源。
if( (connect_fd = accept(socket_fd, (struct sockaddr*)&cilent_addr, &length)) == ⑴){
//客户真个socket地址结构会填写到cilent_addr结构体中
printf("accept socket error: %s(errno: %d)",strerror(errno),errno);
continue;
}
//接受客户端传过来的数据
n = recv(connect_fd, buff, MAXLINE, 0);
if( n < 0 )
{
printf("Server Receive Data Faild!
");
break;
}
//向客户端发送回应数据
if(!fork()){ /*子进程*/
if(send(connect_fd, "Hello,you are connected!
", 26,0) == ⑴)
perror("send error");
close(connect_fd);
exit(0);
}
buff[n] = '