多进程处理tcp客户端demo
头文件
#ifndef __TCP_PROCESS_TEST_H__
#define __TCP_PROCESS_TEST_H__
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#define SERV_PORT 5001
#define SERV_IP_ADDR "192.168.253.130"
#define BACKLOG 5
#define QUIT_STR "quit"
#endif
主程序
1,创建socket fd 2,链接服务器 3,读写数据 4,关闭套接字
#include "net.h"
int main(int argc, char **argv){
int fd = -1;
int port = -1;
struct sockaddr_in sin;
if(argc != 3){
printf("参数错误!\n");
exit(1);
}
1,创建socket fd
if((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
perror("socket");
exit(1);
}
port = atoi (argv[2]);
if(port < 5000){
printf("端口输入错误\n");
exit(1);
}
2,链接服务器
bzero(&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
if(inet_pton(AF_INET, argv[1], (void *) &sin.sin_addr) != 1){
perror("inet_pton");
exit(1);
}
if(connect(fd, (struct sockaddr *) &sin, sizeof(sin)) < 0){
perror("connet");
exit(1);
}
3,读写数据
char buf[BUFSIZ];
int ret = -1;
while(1){
bzero(buf, BUFSIZ);
if(fgets(buf, BUFSIZ -1, stdin) == NULL){
continue;
}
do{
ret = write(fd, buf, strlen(buf));
}while(ret < 0 && EINTR == errno);
if(!strncasecmp(buf, QUIT_STR, strlen(QUIT_STR))){
printf("Client is exiting!\n");
break;
}
}
close(fd);
}
多进程处理tcp服务器端demo:link
|