以下是一个简单的TCP消息封装示例,使用C语言实现:
c复制代码
#include <stdio.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#define SERVER_PORT 8080 | |
#define MAX_BUFFER_SIZE 1024 | |
int main() { | |
int server_fd, new_socket; | |
struct sockaddr_in address; | |
int opt = 1; | |
int addrlen = sizeof(address); | |
char buffer[MAX_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"); | |
exit(EXIT_FAILURE); | |
} | |
address.sin_family = AF_INET; | |
address.sin_addr.s_addr = INADDR_ANY; | |
address.sin_port = htons(SERVER_PORT); | |
// 绑定socket到服务器地址和端口号 | |
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) { | |
perror("bind failed"); | |
exit(EXIT_FAILURE); | |
} | |
// 监听socket连接请求 | |
if (listen(server_fd, 3) < 0) { | |
perror("listen"); | |
exit(EXIT_FAILURE); | |
} | |
printf("Listening on port %d...\n", SERVER_PORT); | |
// 接受客户端连接请求并发送欢迎消息 | |
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) { | |
perror("accept"); | |
exit(EXIT_FAILURE); | |
} | |
printf("Connected to client at address %s:%d\n", inet_ntoa(address.sin_addr), ntohs(address.sin_port)); | |
// 向客户端发送欢迎消息和问候消息 | |
c语言struct用法例子send(new_socket, hello, strlen(hello), 0); | |
send(new_socket, buffer, strlen(buffer), 0); | |
printf("Message sent to client: %s\n", hello); | |
printf("Message sent to client: %s\n", buffer); | |
return 0; | |
} | |
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论