客户端
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#define ERR_MSG(msg) do{\
fprintf(stderr, "__%d__:", __LINE__);\
perror(msg);\
}while(0)
#define SER_PORT 7777
#define SER_IP "192.168.31.212"
int main(int argc, const char *argv[])
{
int cfd = socket(AF_INET,SOCK_STREAM,0);
if(cfd < 0)
{
ERR_MSG("socket");
return -1;
}
struct sockaddr_in sin;
sin.sin_family = AF_INET; //必须填AF_INET;
sin.sin_port = htons(SER_PORT); //服务器绑定的端口
sin.sin_addr.s_addr = inet_addr(SER_IP); //服务器绑定的IP
//连接服务器
if(connect(cfd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
{
ERR_MSG("connect");
return -1;
}
printf("connect success\n");
ssize_t res = 0;
char buf[128] = "";
while(1)
{
bzero(buf, sizeof(buf));
//发送
printf("请输入>>>");
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf)-1] = 0;
if(send(cfd, buf, sizeof(buf), 0) < 0)
{
ERR_MSG("send");
return -1;
}
printf("send success\n");
//接收
res = recv(cfd, buf, sizeof(buf), 0);
if(res < 0)
{
ERR_MSG("recv");
return -1;
}
else if(0 == res)
{
printf("服务器断开连接\n");
break;
}
printf(":%s\n", buf);
}
close(cfd);
return 0;
}
服务器
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#define ERR_MSG(msg) do{\
fprintf(stderr, "__%d__:", __LINE__);\
perror(msg);\
}while(0)
#define PORT 7777
#define IP "192.168.31.212"
int main(int argc, const char *argv[])
{
//创建流式套接字
int sfd = socket(AF_INET,SOCK_STREAM,0);
if(sfd < 0)
{
ERR_MSG("socket");
return -1;
}
//允许端口快速被重用
int reuse = 1;
if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse ,sizeof(reuse)) < 0)
{
ERR_MSG("setsockopt");
return -1;
}
printf("允许端口快速重用\n");
//填充地址信息结构体,真是的地址信息结构体根据地址族制定
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr = inet_addr(IP);
//将地址信息结构体绑定到套接字上
if(bind(sfd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
{
ERR_MSG("bind");
return -1;
}
//将套接字设置为被动监听状态
if(listen(sfd, 128) < 0)
{
ERR_MSG("listen");
return -1;
}
struct sockaddr_in cin; //存储连接成功的客户端信息
socklen_t addrlen = sizeof(cin);
//accept从队列头中获取一个客户端信息
int newfd = accept(sfd, (struct sockaddr*)&cin, &addrlen);
if(newfd < 0)
{
ERR_MSG("accept");
return -1;
}
printf("[%s:%d] newfd = %d 连接成功\n",inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd);
ssize_t res = 0;
char buf[128] = "";
while(1)
{
bzero(buf, sizeof(buf));
//接收
res = recv(newfd, buf, sizeof(buf), 0);
if(res < 0)
{
ERR_MSG("recv");
return -1;
}
else if(0 == res)
{
printf("[%s:%d] newfd = %d 客户端断开连接\n",inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd);
break;
}
printf("[%s:%d] newfd = %d : %s\n",inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd, buf);
//发送
//将获取到的数据拼接后发送回去
strcat(buf, "^_^");
if(send(newfd, buf, sizeof(buf), 0) < 0)
{
ERR_MSG("send");
return -1;
}
printf("send success\n");
}
close(newfd);
close(sfd);
return 0;
}