linux c socket编程回顾二:简单服务端、客户端
程序员文章站
2022-06-06 08:29:59
...
通过上篇的讲解,我没可以写一个简单的服务端:
这里仍有一些可圈点之处:
-
INADDR_ANY,转换过来就是0.0.0.0,是指本机所有ip,比如本机有多个网卡多个ip,只需绑定某个ip的地址,只能监听某个网卡过来的消息,这里INADDR_ANY,监听所有网卡的消息
- inet_addr()将一个字符串类型的ip地址比如“192.168.0.100”转化为uint32_t数字格式,因为网络传输地址用的是uint32_t格式
- socket默认都是阻塞的,连接、收、发,其中连接有个系统超时时间,到达后还没建立连接才返回失败;读写则会一直阻塞,直到数据到来;那怎样改为非阻塞呢?下篇单独介绍
#include <sys/socket.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#define PORT 10102
int main()
{
int sockfd;
int client_fd;
//socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if( sockfd < 0 )
{
perror("socket error!");
return -1;
}
//bind
struct sockaddr_in client_addr, server_addr;
memset(&server_addr, 0x00, sizeof(struct sockaddr_in));
server_addr.sin_family=AF_INET; //协议
server_addr.sin_addr.s_addr=INADDR_ANY; //服务器地址--允许链接到本地任何地址
server_addr.sin_port=htons(PORT);
if(bind(sockfd, (struct sockaddr*)&server_addr, sizeof(struct sockaddr)) < 0)
{
perror("bind error!");
return -1;
}
//listen
listen(sockfd, 5); //5也是系统的默认值
printf("start listen......\n");
//accept 接收客户端收链接
int size = sizeof(struct sockaddr_in);
if( (client_fd = accept(sockfd, (struct sockaddr *)&client_addr, &size)) < 0)
{
perror("accept error!");
return -1;
}
printf("accept client %s\n",inet_ntoa(client_addr.sin_addr));
send(client_fd, "welcome\n", 8, 0);
//recv/send
int n;
char buf[1024]={0};
while((n = recv(client_fd, buf, 1024, 0)) > 0)
{
buf[n] = '\0';
printf("%s\n", buf);
if(send(client_fd, buf, n, 0) < 0)
{
perror("error send!");
return -1;
}
}
close(client_fd);
close(sockfd);
return 0;
}
简单的客户端
#include <sys/socket.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#define PORT 10102
int main()
{
int sockfd;
int client_fd;
//socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if( sockfd < 0 )
{
perror("socket error!");
return -1;
}
struct sockaddr_in server_addr;
memset(&server_addr, 0x00, sizeof(struct sockaddr_in));
server_addr.sin_family=AF_INET; //协议
server_addr.sin_addr.s_addr=inet_addr("127.0.0.1"); //服务器地址
server_addr.sin_port=htons(PORT);
//connect
if(connect(sockfd, (struct sockaddr*)&server_addr, sizeof(struct sockaddr)) < 0)
{
perror("connect error!");
return -1;
}
//recv/send
char buf[1024]={0};
printf("connected to server\n");
recv(sockfd, buf, 1024, 0);
printf("%s\n",buf);
int n;
while(1)
{
memset(buf, 0x00, sizeof(buf));
printf("Enter string to send:");
scanf("%s",buf);
if(strncmp(buf,"quit", 4) == 0)
break;
n = send(sockfd, buf, strlen(buf), 0);
n = recv(sockfd, buf, 1024,0);
buf[n]='\0';
printf("recv:[%s]\n", buf);
}
close(sockfd);
return 0;
}