服务器端
#include <iostream>
#include <string.h> // memset
#include <sys/socket.h>
#include <arpa/inet.h> // inet_addr
#include <unistd.h> // close
int main(int argc, char *argv[])
{
int server_socket, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[1024] = {0};
const char* response = "欢迎访问!";
// 创建 socket
if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// 设置地址结构
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( 9999 );
// 绑定 socket 到端口
if (bind(server_socket, (struct sockaddr *)&address,
sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听连接
if (listen(server_socket, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
// 接受连接
if ((new_socket = accept(server_socket, (struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
// 发送数据
send(new_socket , response , strlen(response) , 0 );
printf("消息发送完毕\n");
// 关闭 socket
close(new_socket);
close(server_socket);
return 0;
}
客户端
#include <iostream>
#include <string.h> // memset
#include <sys/socket.h>
#include <arpa/inet.h> // inet_addr
#include <unistd.h> // close
int main(int argc, char *argv[])
{
int sock = 0, valread;
struct sockaddr_in serv_addr;
const char* message = "Hello Server";
char buffer[1024] = {0};
// 创建 socket
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
// 设置服务器地址
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(9999);
// 转换 IPv4 和 IPv6 地址
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
// 连接到服务器
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
// 发送数据
send(sock , message , strlen(message) , 0 );
printf("消息发送完毕\n");
// 接收数据
valread = read( sock , buffer, 1024);
printf("%s\n",buffer );
// 关闭 socket
close(sock);
return 0;
}