56 lines
1.4 KiB
C
56 lines
1.4 KiB
C
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
#include <unistd.h>
|
||
|
#include <arpa/inet.h>
|
||
|
|
||
|
#define PORT 8001
|
||
|
#define BUFFER_SIZE 1024
|
||
|
|
||
|
int main() {
|
||
|
int client_socket;
|
||
|
struct sockaddr_in server_addr;
|
||
|
char buffer[BUFFER_SIZE];
|
||
|
|
||
|
// 创建客户端 socket
|
||
|
client_socket = socket(AF_INET, SOCK_STREAM, 0);
|
||
|
if (client_socket == -1) {
|
||
|
perror("客户端 socket 创建失败");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
// 设置服务器地址
|
||
|
server_addr.sin_family = AF_INET;
|
||
|
server_addr.sin_port = htons(PORT);
|
||
|
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
|
||
|
|
||
|
// 连接到服务器
|
||
|
if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
|
||
|
perror("连接服务器失败");
|
||
|
close(client_socket);
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
printf("连接服务器成功!\n");
|
||
|
|
||
|
while (1) {
|
||
|
printf("输入要发送的消息: ");
|
||
|
fgets(buffer, BUFFER_SIZE, stdin);
|
||
|
buffer[strcspn(buffer, "\n")] = 0; // 去掉换行符
|
||
|
|
||
|
send(client_socket, buffer, strlen(buffer), 0);
|
||
|
|
||
|
if (strcmp(buffer, "exit") == 0) {
|
||
|
break;
|
||
|
}
|
||
|
|
||
|
int bytes_read = recv(client_socket, buffer, sizeof(buffer) - 1, 0);
|
||
|
if (bytes_read > 0) {
|
||
|
buffer[bytes_read] = '\0';
|
||
|
printf("服务器回复: %s\n", buffer);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
close(client_socket);
|
||
|
return 0;
|
||
|
}
|