1、服务端
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#define PORT 8111
#define MESSAGE_LEN 1024
int main(int argc, char* argv[])
{
int socket_fd, accept_fd;
int on = 1;
int ret = -1;
int backlog = 10;
struct sockaddr_in localaddr,remoteaddr;
char in_buff[MESSAGE_LEN] = {0,};
socket_fd = socket(PF_INET, SOCK_STREAM, 0);
if (socket_fd == -1){
std::cout << "create socket failed" << std::endl;
exit(-1);
}
ret = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
if (ret == -1){
std::cout << "failed set socket options" << std::endl;
exit(-1);
}
localaddr.sin_family = AF_INET;
localaddr.sin_port = PORT;
localaddr.sin_addr.s_addr = INADDR_ANY;
bzero(&(localaddr.sin_zero), 8);
ret = bind(socket_fd, (struct sockaddr *)&localaddr, sizeof(struct sockaddr));
if (ret == -1){
std::cout << "failed to bin addr" << std::endl;
exit(-1);
}
ret = listen(socket_fd, backlog);
if (ret == -1){
std::cout << "failed to listen addr" << std::endl;
exit(-1);
}
for(;;){
socklen_t addr_len = sizeof(struct sockaddr);
accept_fd = accept(socket_fd, (struct sockaddr *)&remoteaddr, &addr_len);
for (;;){
ret = recv(accept_fd, (void *)in_buff, MESSAGE_LEN, 0);
if (ret == 0){
std::cout << "quit" << std::endl;
break;
}
std::cout << "recv: " << in_buff << std::endl;
send(accept_fd, (void*)in_buff,MESSAGE_LEN, 0);
}
close(accept_fd);
}
close(socket_fd);
}
二、客户端
#include<iostream>
#include<stdio.h>
#include <cstring>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#define PORT 8111
#define MESSAGE_LEN 1024
int main(int argc, char*argv[])
{
int ret = -1;
int socket_fd;
struct sockaddr_in serveraddr;
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
char sendbuf[MESSAGE_LEN] = {0,};
char recvbuf[MESSAGE_LEN] = {0,};
if (socket_fd < 0){
std::cout << "failed to create socket" << std::endl;
exit(-1);
}
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = PORT;
serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = connect(socket_fd, (struct sockaddr *)&serveraddr, sizeof(struct sockaddr));
if (ret < 0){
std::cout << "failed to connect socket" << std::endl;
exit(-1);
}
while(1){
memset(sendbuf, 0, MESSAGE_LEN);
std::cin.getline(sendbuf, MESSAGE_LEN);
ret = send(socket_fd, sendbuf, strlen(sendbuf), 0);
if (ret < 0){
std::cout << "failed to send socket" << std::endl;
break;
}
if (strcmp(sendbuf, "quit") == 0){
std::cout << "quit" << std::endl;
break;
}
ret = recv(socket_fd, recvbuf, MESSAGE_LEN, 0);
recvbuf[ret] = '\0';
std::cout << "recv:" << recvbuf << std::endl;
}
close(socket_fd);
}
三、效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fd0e4ca2853bd3f91d23eecbd4b7d22c.png)