网络编程模型——基础模板
Posted _BitterSweet
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了网络编程模型——基础模板相关的知识,希望对你有一定的参考价值。
server.c 服务器端
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/socket.h>
#include<arpa/inet.h>
void error_handling(char *message)
fputs(message, stderr);
fputc('\\n', stderr);
exit(1);
int main(int argc, char *argv[])
int server_sock;
int client_sock;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
socklen_t client_addr_size;
char message[] = "hello world!";
if(argc != 2)
printf("Usage : %s <port>\\n", argv[0]);
// 创建套接字
server_sock = socket(PF_INET, SOCK_STREAM, 0);
if(server_sock == -1)
error_handling("socket create error");
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(atoi(argv[1]));
//调用bind函数分配ip地址和端口号
if(bind(server_sock, (struct sockaddr*) &server_addr, sizeof(server_addr)) == -1)
error_handling("bind error");
//listen:将套接字转为可接受连接状态
if(listen(server_sock, 5) == -1)
error_handling("listen error");
client_addr_size = sizeof(client_addr);
//accept函数:处理连接请求,没有连接的情况下调用该函数,则不会返回
client_sock = accept(server_sock, (struct sockaddr*) &client_addr, &client_addr_size);
if(client_sock == -1)
error_handling("accept error");
//write:用于传输数据
write(client_sock, message, sizeof(message));
close(client_sock);
close(server_sock);
return 0;
client.c 客户端
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/socket.h>
#include<arpa/inet.h>
void error_handling(char *message)
fputs(message, stderr);
fputc('\\n', stderr);
exit(1);
int main(int argc, char *argv[])
int sock;
struct sockaddr_in server_addr;
char message[128];
int str_len;
if(argc != 3)
printf("Usage : %s <ip> <port>\\n", argv[0]);
exit(1);
sock = socket(PF_INET, SOCK_STREAM, 0);
if(sock == -1)
error_handling("socket create error");
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(argv[1]);
server_addr.sin_port = htons(atoi(argv[2]));
if(connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1)
error_handling("connect error");
str_len = read(sock, message, sizeof(message) - 1);
if(str_len == -1)
error_handling("read error");
printf("Message from server : %s \\n", message);
close(sock);
return 0;
执行方式:
- gcc server.c -o server / gcc client.c -o client
- ./server 8080
- ./client 127.0.0.1 8080
- message可以自定义发送消息内容
以上是关于网络编程模型——基础模板的主要内容,如果未能解决你的问题,请参考以下文章