Linux/Unix服务端和客户端Socket编程入门实例(含源码下载)
1. 源程序
1.1 client
#include "head.h"
int main(int argc, char **argv)
{
struct sockaddr_in servaddr;
int status, sockfd,count;
int fd[20];
int index = 0;
int flag = 1;
count = atoi(argv[1]);
while (count-- > 0) {
fd[index] = socket(AF_INET, SOCK_STREAM, 0);
sockfd = fd[index];
index++;
if(sockfd < 0){
perror("socket() error");
exit(1);
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
status = inet_pton(AF_INET, "10.10.37.15", &servaddr.sin_addr);
if(status <= 0){
perror("inet_pton() error");
exit(1);
}
setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(flag));
if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0){
close(sockfd);
printf("%s......\n", strerror(errno));
return -1;
} else {
printf("i=%d,fd:%d, ESTABLISHED.\n", index-1, sockfd);
}
}
pause();
return 0;
}
1.2 server
#include "head.h"
int main(int argc, char **argv)
{
int listenfd, sockfd,ret;
struct sockaddr_in servaddr;
char *buf = "serverritethis";
char recv_buf[20];
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if(listenfd < 0){
perror("socket() error......\n");
exit(1);
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0){
perror("bind() error......\n");
exit(1);
}
if(listen(listenfd, 4) < 0){
perror("listen() error......\n");
exit(1);
}
printf("listening...\n");
while(1){
sleep(1);
}
exit(0);
}