socket tcp发送接收 C代码
时间: 2024-10-17 10:15:03 浏览: 36
在C语言中,Socket编程通常用于TCP/IP网络通信,下面是一个简单的客户端和服务器的例子,展示了如何通过TCP发送和接收数据:
**服务器端(server.c):**
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
int server_fd, client_sock;
struct sockaddr_in server_addr, client_addr;
socklen_t addr_len = sizeof(struct sockaddr_in);
// 创建套接字
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket failed");
return 1;
}
// 设置服务器地址
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT); //假设SERVER_PORT已定义
inet_pton(AF_INET, "localhost", &server_addr.sin_addr);
// 绑定并监听
if (bind(server_fd, (struct sockaddr *)&server_addr, addr_len) == -1) {
perror("bind failed");
close(server_fd);
return 1;
}
listen(server_fd, MAX_CONNECTIONS);
// 接受连接
if ((client_sock = accept(server_fd, (struct sockaddr *)&client_addr, &addr_len)) == -1) {
perror("accept failed");
close(server_fd);
return 1;
}
char buffer[1024];
printf("Server: Waiting for message...\n");
// 读取客户端消息
ssize_t bytes_received = recv(client_sock, buffer, sizeof(buffer), 0);
if (bytes_received > 0) {
buffer[bytes_received] = '\0';
printf("Server: Received: %s\n", buffer);
send(client_sock, "Server received your message.", strlen("Server received your message."), 0);
} else {
perror("recv failed");
}
close(client_sock);
close(server_fd);
return 0;
}
```
**客户端(client.c):**
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SERVER_IP "localhost"
#define SERVER_PORT 12345 // 假设服务器使用的端口
int main() {
int client_sock;
struct sockaddr_in server_addr;
socklen_t addr_len = sizeof(struct sockaddr_in);
// 创建套接字
if ((client_sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket failed");
return 1;
}
// 设置客户端地址
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr);
// 连接到服务器
if (connect(client_sock, (struct sockaddr *)&server_addr, addr_len) == -1) {
perror("connect failed");
close(client_sock);
return 1;
}
char input[1024];
printf("Client: Enter a message to send: ");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = '\0'; // remove newline character
// 发送消息
if (send(client_sock, input, strlen(input), 0) == -1) {
perror("send failed");
}
printf("Client: Sent: %s\n", input);
// 接收服务器响应
char response[1024];
ssize_t bytes_received = recv(client_sock, response, sizeof(response), 0);
if (bytes_received > 0) {
response[bytes_received] = '\0';
printf("Client: Received from Server: %s\n", response);
} else {
perror("recv failed");
}
close(client_sock);
return 0;
}
```
阅读全文