1.服务器端的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE] = {0};
char *hello = "Hello from server";
// 创建socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 设置socket选项
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt failed");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// 绑定地址和端口
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听连接
if (listen(server_fd, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
// 接受连接并处理请求
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// 读取客户端发来的消息
valread = read(new_socket, buffer, BUFFER_SIZE);
printf("%s\n",buffer);
// 向客户端发送消息
send(new_socket , hello , strlen(hello) , 0);
printf("Hello message sent\n");
return 0;
}
创建了一个简单的服务器,监听8080端口,并接受客户端的连接。一旦建立连接,服务器将读取客户端发送的消息,并向客户端发送消息。
gcc ./server.c -o server
./server
2.客户端的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define MAX_BUFFER_SIZE 1024
int main() {
int sock;
struct sockaddr_in server_addr;
char buffer[MAX_BUFFER_SIZE];
// 创建套接字
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
// 设置服务器地址信息
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080); // 服务器端口
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 服务器IP地址
// 连接服务器
if (connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("connect");
exit(EXIT_FAILURE);
}
// 发送数据到服务器
char *message = "Hello, server!";
if (send(sock, message, strlen(message), 0) == -1) {
perror("send");
exit(EXIT_FAILURE);
}
// 接收服务器的响应
memset(buffer, 0, sizeof(buffer));
if (recv(sock, buffer, sizeof(buffer) - 1, 0) == -1) {
perror("recv");
exit(EXIT_FAILURE);
}
printf("Server response: %s\n", buffer);
// 关闭套接字
close(sock);
return 0;
}
创建了一个套接字,然后设置服务器的地址信息,包括服务器的IP地址和端口号。接下来,我们使用connect
函数来连接服务器。如果连接成功,我们就可以使用send
函数向服务器发送数据,使用recv
函数接收服务器的响应。最后,我们关闭套接字。
gcc ./client.c -o client
./client