用codeclosks的c语言完成一个基于socket网络编程的信息收发程序。要求如下: 1单机同时模拟完成服务器端和客户端的功能即可; 2功能要求客户端发一条消息,服务器端收到对应得消息
时间: 2024-02-06 07:10:44 浏览: 66
以下是一个基于socket网络编程的信息收发程序的示例,使用C语言编写。
服务器端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 8888
#define MAX_MSG_LEN 1024
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[MAX_MSG_LEN] = {0};
const char *response = "Message received.";
// 创建套接字
if ((server_fd = 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(PORT);
// 绑定套接字到指定的地址和端口
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听套接字,等待客户端连接
if (listen(server_fd, 1) < 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);
}
// 接收客户端发送的消息
int valread = read(new_socket, buffer, MAX_MSG_LEN);
printf("Received message: %s\n", buffer);
// 发送响应消息给客户端
send(new_socket, response, strlen(response), 0);
printf("Response sent.\n");
return 0;
}
```
客户端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 8888
#define MAX_MSG_LEN 1024
int main() {
int sock = 0, valread;
struct sockaddr_in serv_addr;
char *message = "Hello from client.";
char buffer[MAX_MSG_LEN] = {0};
// 创建套接字
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(PORT);
// 将IPv4地址从点分十进制转换为网络字节序
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("Message sent.\n");
// 接收服务器响应消息
valread = read(sock, buffer, MAX_MSG_LEN);
printf("Response received: %s\n", buffer);
return 0;
}
```
运行以上代码后,服务器端将等待客户端连接,并在接收到客户端发送的消息后发送响应消息给客户端。客户端将连接服务器,并发送一条消息,然后等待服务器响应消息。程序运行结束后,客户端将输出服务器发送的响应消息。
阅读全文