在linux中通過流式套接字程式設計(tcp),實現乙個併發伺服器的訪問回顯,適合剛學完linux套接字程式設計的朋友進行鞏固訓練
具體功能:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define server_addr "172.17.44.154"
#define bufsize 100
void
sigchld_handler
(int arg)
;int
main
(int argc,
const
char
*ar**)
/* 繫結位址 */
server_addr.sin_family = af_inet;
server_addr.sin_port =
htons
(5001);
inet_pton
(af_inet, server_addr,
(void*)
&server_addr.sin_addr.s_addr)
;//位址轉換if(
-1==bind
(socket_fd,
(struct sockaddr*
)&server_addr,
sizeof
(server_addr)))
/* 轉換為被動連線套接字 */if(
-1==listen
(socket_fd,5)
)#if 0
//單程序伺服器
/* 獲取已連線套接字 */
socklen_t len =0;
new_fd =
accept
(socket_fd,
(struct sockaddr*
)&cli_addr,
(socklen_t *
)&len);if
(-1== new_fd)
printf
("accept socket!\nclient ip :%s port:%d\n"
,inet_ntoa
(cli_addr.sin_addr)
, cli_addr.sin_port)
;while(1
)printf
("read:%s\n"
, buf)
;send
(new_fd, buf, bufsize,0)
;//回應客戶端
}close
(new_fd)
;#else
//多程序併發伺服器
while(1
)/* 併發伺服器:子程序中進行tcp通訊 */
pid =
fork()
;if(pid ==-1
)else
if(pid ==0)
getsockname
(new_fd,
(struct sockaddr*
)&cli_addr,
(socklen_t *
)&len)
;//獲取連線套接字資訊
printf
("recv client ip:%s data:%s\n"
,inet_ntoa((
struct in_addr)cli_addr.sin_addr)
, buf)
;send
(new_fd, buf, bufsize,0)
;//回應客戶端}}
else
}#endif
close
(socket_fd)
;return0;
}void
sigchld_handler
(int arg)
printf
("a client %d is end\n"
, child_pid);}
}
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define server_addr "172.17.44.154"
#define bufsize 100
intmain
(int argc,
const
char
*ar**)
server_addr.sin_family = af_inet;
server_addr.sin_port =
htons
(5001);
inet_pton
(af_inet, server_addr,
(void*)
&server_addr.sin_addr.s_addr);if
(-1==
connect
(new_fd,
(struct sockaddr*
)&server_addr,
sizeof
(server_addr)))
while(1
)if(0
==recv
(new_fd, buf, bufsize,0)
)printf
("recv:%s\n"
, buf);}
close
(new_fd)
;return0;
}
ps:這裡是在同一主機下做實驗的,所以各個客戶端的ip位址都是一樣的
正常執行的狀態如下:
當有乙個客戶端退出時,伺服器會顯示資訊,但是對其他客戶端的服務正常進行:
當伺服器主動關閉之後,所有客戶端都會收到伺服器關閉的資訊,並且主動退出:
Linux 併發伺服器程式設計(多程序)
在linux中通過流式套接字程式設計 tcp 實現乙個併發伺服器的訪問回顯,適合剛學完linux套接字程式設計的朋友進行鞏固訓練 具體功能 include include include include include include include include include include ...
linux網路程式設計多程序併發伺服器
伺服器端 include include include include include include include include define port 1234 define maxsize 1024 static int clientprocess int connfd,struct s...
linux多程序併發伺服器
多程序併發伺服器,多執行緒版 include include include include include include include include include include include 程序 函式 void recyle int num int main int argc,cha...