程序流程:
服务器程序流程(多进程):
- 程序初始化
- 填写本机地址信息
- 绑定并监听一个固定的端口
- 收到Client的连接后建立一个socket连接
- 产生一个新的进程与Client进行通信和信息处理
- 子通信结束后中断与Client的连接
客户端程序流程:
- 程序初始化
- 填写服务器地址信息
- 连接服务器
- 与服务器通信和信息处理
- 通信结束后断开连接
服务器程序:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#define MYPORT 3490 /* 监听的端口 */
#define BACKLOG 10 /* listen的请求接收队列长度 */
void main() {
int sockfd, new_fd; /* 监听端口,数据端口 */
struct sockaddr_in sa; /* 自身的地址信息 */
struct sockaddr_in their_addr; /* 连接对方的地址信息 */
int sin_size;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
sa.sin_family = AF_INET;
sa.sin_port = htons(MYPORT); /* 网络字节顺序 */
sa.sin_addr.s_addr = INADDR_ANY; /* 自动填本机IP */
bzero(&(sa.sin_zero), 8); /* 其余部分置0 */
if (bind(sockfd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
perror("bind");
exit(1);
}
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
/* 主循环 */
while(1) {
sin_size = sizeof(struct sockaddr_in);
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size))
if (new_fd == -1) {
perror("accept");
continue;
}
printf(”Got connection from %s/n", inet_ntoa(their_addr.sin_addr));
if (fork() == 0) {
/* 子进程 */
if (send(new_fd, "Hello, world!/ n", 14, 0) == -1)
perror("send");
close(new_fd);
exit(0);
}
close(new_fd);
/*清除所有子进程 */
while(waitpid(-1,NULL,WNOHANG) > 0);
}
}
客户端程序:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define PORT 3490 /* Server的端口 */
#define MAXDATASIZE 100 /*一次可以读的最大字节数 */
int main(int argc, char *argv[])
{
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct hostent *he; /* 主机信息 */
struct sockaddr_in their_addr; /* 对方地址信息 */
if (argc != 2) {
fprintf(stderr,"usage: client hostname/n");
exit(1);
}
/* get the host info */
if ((he=gethostbyname(argv[1])) == NULL) {
/* 注意:获取DNS信息时,显示出错需要用herror而不是perror */
herror("gethostbyname");
exit(1);
}
if ((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1) {
perror("socket");
exit(1);
}
their_addr.sin_family = AF_INET;
their_addr.sin_port = htons(PORT); /* short, NBO */
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
bzero(&(their_addr.sin_zero), 8); /* 其余部分设成0 */
if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) {
perror("connect");
exit(1);
}
if ((numbytes=recv(sockfd,buf,MAXDATASIZE,0))==-1) {
perror("recv");
exit(1);
}
buf[numbytes] = '/0';
printf("Received: %s",buf);
close(sockfd);
return 0;
}