#include
#include
#include
#include
#include
#include
#include
#include
#define SERV_PORT 25555 //服務器接聽端口號
#define BACKLOG 20 //請求隊列中允許請求數(shù)
#define BUF_SIZE 256 //緩沖區(qū)大小
int main(int argc,char *argv[])
{
int ret;
time_t tt;
struct tm *ttm;
char buf[BUF_SIZE];
pid_t pid; //定義管道描述符
int sockfd; //定義sock描述符
int clientfd; //定義數(shù)據(jù)傳輸sock描述符
struct sockaddr_in host_addr; //本機IP地址和端口信息
struct sockaddr_in client_addr; //客戶端IP地址和端口信息
int length = sizeof client_addr;
//創(chuàng)建套接字
sockfd = socket(AF_INET, SOCK_STREAM, 0); //TCP/IP協(xié)議,數(shù)據(jù)流套接字
if(sockfd == -1) //判斷socket函數(shù)的返回值
{
printf("創(chuàng)建socket失敗.\n");
return 0;
}
//綁定套接字
bzero(&host_addr, sizeof host_addr);
host_addr.sin_family = AF_INET; //TCP/IP協(xié)議
host_addr.sin_port = htons(SERV_PORT); //設定端口號
host_addr.sin_addr.s_addr = INADDR_ANY; //本地IP地址
ret = bind(sockfd, (struct sockaddr *)&host_addr, sizeof host_addr); //綁定套接字
if(ret == -1) //判斷bind函數(shù)的返回值
{
printf("調用bind失敗.\n");
return 1;
}
//監(jiān)聽網(wǎng)絡端口
ret = listen(sockfd, BACKLOG);
if(ret == -1) //判斷l(xiāng)isten函數(shù)的返回值
{
printf("調用listen函數(shù)失敗.\n");
return 1;
}
while(1)
{
clientfd = accept(sockfd, (struct sockaddr *)&client_addr, &length); //接收接連請求
if(clientfd == -1)
{
printf("調用accept接受連接失敗.\n");
return 1;
}
pid = fork(); //創(chuàng)建子進程
if(pid == 0) //在子進程是處理
{
while(1)
{
bzero(buf, sizeof buf); //首先清空緩沖區(qū)
tt = time(NULL);
ttm = localtime(&tt); //獲取當前時間參數(shù)
strcpy(buf, asctime(ttm)); //將時間信息copy進緩沖區(qū)
send(clientfd, buf, strlen(buf), 0); //發(fā)送數(shù)據(jù)
sleep(2);
}
close(clientfd); //調用close函數(shù)關閉連接
}
else if(pid > 0)
{
close(clientfd); //父進程關閉套接字,準備下一個客戶端連接
}
}
return 0;
}
文章題目:[Linux網(wǎng)絡編程]TCP編程--TCP通信程序服務器端
轉載來于:
http://weahome.cn/article/jsdjgo.html