#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define BUFFER_SIZE 1024 int main(int argc, char *argv[]) { int client_socket; struct sockaddr_in server_addr; char buffer[BUFFER_SIZE]; char *server_ip = "127.0.0.1"; int port = 8888; if(argc > 2) { server_ip = argv[1]; port = atoi(argv[2]); } client_socket = socket(AF_INET, SOCK_STREAM, 0); if(client_socket == -1) { perror("socket"); exit(EXIT_FAILURE); } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(server_ip); server_addr.sin_port = htons(port); if(connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) { perror("connect"); exit(EXIT_FAILURE); } printf("Connected to server %s:%d\n", server_ip, port); while(1) { fgets(buffer, BUFFER_SIZE, stdin); buffer[strlen(buffer) - 1] = '\0'; if(strcmp(buffer, "quit") == 0) { break; } int send_len = send(client_socket, buffer, strlen(buffer), 0); if(send_len == -1) { perror("send"); break; } } close(client_socket); return 0; }进行注释
时间: 2024-02-05 20:03:59 浏览: 328
这是一个简单的客户端程序,使用TCP协议连接到指定的服务器。
1. 包含必要的头文件
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFFER_SIZE 1024
```
2. 定义主函数
```
int main(int argc, char *argv[]) {
```
3. 初始化变量
```
int client_socket;
struct sockaddr_in server_addr;
char buffer[BUFFER_SIZE];
char *server_ip = "127.0.0.1";
int port = 8888;
if(argc > 2) {
server_ip = argv[1];
port = atoi(argv[2]);
}
```
其中,client_socket是客户端的套接字文件描述符;server_addr是服务器的IP地址和端口号;buffer用于存储发送数据;server_ip和port默认为127.0.0.1和8888,也可以通过命令行参数进行修改。
4. 创建socket
```
client_socket = socket(AF_INET, SOCK_STREAM, 0);
if(client_socket == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
```
创建一个TCP套接字。
5. 初始化服务器地址
```
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(server_ip);
server_addr.sin_port = htons(port);
```
将server_addr的各个字段赋值。
6. 连接到服务器
```
if(connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("connect");
exit(EXIT_FAILURE);
}
printf("Connected to server %s:%d\n", server_ip, port);
```
通过connect函数连接到服务器。
7. 发送数据
```
while(1) {
fgets(buffer, BUFFER_SIZE, stdin);
buffer[strlen(buffer) - 1] = '\0';
if(strcmp(buffer, "quit") == 0) {
break;
}
int send_len = send(client_socket, buffer, strlen(buffer), 0);
if(send_len == -1) {
perror("send");
break;
}
}
```
从标准输入获取用户输入的数据,然后将其发送到服务器。如果用户输入了"quit",则退出循环。如果发送数据失败,则退出循环。
8. 关闭socket
```
close(client_socket);
return 0;
```
关闭客户端的socket。
完整代码如下:
阅读全文