套接字可以讓Linux在網絡上通信,用起來就像管道一樣,當然管道都是單向的,套接字既能寫也能收!
以下是多客戶服務器代碼:
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <signal.h>
- #include <arpa/inet.h>
- #include <string.h>
- #define PORT 6000
- #define SIZE 256
-
- static void handler()//回收子進程函數
- {
- wait(NULL);
- }
-
- int main(int argc, char **argv)
- {
- int server_socketfd;
- int client_socketfd;
- int ret;
- pid_t pid;
- size_t address_len;
- struct sockaddr_in server_address;
- struct sockaddr_in client_address;
-
- server_socketfd = socket(AF_INET, SOCK_STREAM,0);//創建一個套接字
-
- memset(&server_address,0,sizeof(struct sockaddr_in));
-
- server_address.sin_family = AF_INET;//協議族設置為ARPA因特網協議
- server_address.sin_port = htons(PORT);//端口號設為PORT(6000)
- server_address.sin_addr.s_addr = htonl(INADDR_ANY);//允許任何客戶端可以連接
- address_len = sizeof(struct sockaddr_in);
-
- ret = bind(server_socketfd, (struct sockaddr*)&server_address, address_len);//將創建的套接字和address中的地址綁定在一起
- if( ret == -1 )
- {
- printf("bind failed!\n");
- exit(0);
- }
-
- ret = listen(server_socketfd, 5);//創建一個監聽5個請求的隊列,也就是說這個服務器允許5個人同時登入
- if ( ret == -1 )
- {
- printf("listen failed!\n");
- exit(0);
- }
-
- while (1)
- {
- client_socketfd = accept(server_socketfd, (struct sockaddr*)&client_address, &address_len);//客戶連接服務器時建立客戶套接字
-
- signal(SIGCHLD,handler);//為了避免子進程結束時造成僵屍進程,需要對結束子進程作處理,handler函數負責回收子進程
-
- pid = fork();
- if (pid == 0)//為客戶分配的子進程
- {
- char buffer[256];
- int nread;
- nread = read(client_socketfd,buffer,sizeof(buffer));
- printf("%s",buffer);
-
- }
- else if (pid > 0)//父進程把分配的客戶套接字關閉,用來供給下個客戶
- {
- close(client_socketfd);//關閉客戶套接字
- }
- else
- {
- printf("fork faild!\n");
- exit(0);
- }
- }
- return 0;
- }
客戶端代碼:
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <string.h>
-
- #define SIZE 256
- #define PORT 6000
-
- int main()
- {
- int socketfd;
- int ret;
- char buffer[SIZE];
- struct sockaddr_in address;
-
- socketfd = socket(AF_INET, SOCK_STREAM, 0);//創建一個套接字
-
- address.sin_family = AF_INET;//設置為因特網協議
- address.sin_port = htons(PORT);//設置端口號
- inet_pton(AF_INET, "127.0.0.1", &address.sin_addr.s_addr);//設置ip地址
-
- ret = connect(socketfd, (struct sockaddr*) &address, sizeof(address));//連接服務器
-
- if (ret == -1)
- {
- printf("can't connect!\n");
- exit(0);
- }
-
- printf("send:");
- fgets(buffer,sizeof(buffer),stdin);
- write(socketfd,buffer,sizeof(buffer));//把數據傳給服務器
-
- close(socketfd);//關閉套接字
- return 0;
- }