基于Linux的C或C++代码实现
时间: 2024-03-27 21:37:37 浏览: 58
好的,以下是基于Linux的C语言代码实现:
服务端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#define PORT 8000
void handle_request(int client_socket) {
char buf[1024];
int len = recv(client_socket, buf, sizeof(buf), 0);
if (len == -1) {
perror("recv");
return;
}
buf[len] = '\0';
if (strcmp(buf, "liu") == 0) {
send(client_socket, "Hello, You are connected!", 26, 0);
} else {
send(client_socket, "Sorry, you are not the user!", 29, 0);
}
printf("Received from client: %s\n", buf);
close(client_socket);
}
int main() {
int server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
int client_len = sizeof(client_addr);
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
perror("socket");
exit(1);
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(PORT);
if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("bind");
exit(1);
}
if (listen(server_socket, 1) == -1) {
perror("listen");
exit(1);
}
printf("Server listening on port %d\n", PORT);
while (1) {
client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_len);
if (client_socket == -1) {
perror("accept");
continue;
}
printf("Connected from %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
handle_request(client_socket);
}
close(server_socket);
return 0;
}
```
客户端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#define PORT 8000
int main() {
int client_socket;
struct sockaddr_in server_addr;
client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket == -1) {
perror("socket");
exit(1);
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(PORT);
if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("connect");
exit(1);
}
char user[1024];
printf("Enter your username: ");
scanf("%s", user);
if (send(client_socket, user, strlen(user), 0) == -1) {
perror("send");
exit(1);
}
char buf[1024];
int len = recv(client_socket, buf, sizeof(buf), 0);
if (len == -1) {
perror("recv");
exit(1);
}
buf[len] = '\0';
printf("%s\n", buf);
close(client_socket);
return 0;
}
```
使用方法:
1. 打开终端,进入服务端代码所在目录,输入命令:`gcc server.c -o server`,编译服务端程序,生成可执行文件;
2. 再输入命令:`./server`,启动服务端程序,服务端就会在本地8000端口监听客户端连接;
3. 打开另一个终端,进入客户端代码所在目录,输入命令:`gcc client.c -o client`,编译客户端程序,生成可执行文件;
4. 再输入命令:`./client`,客户端会要求输入用户名,输入后按回车键发送给服务端;
5. 服务端接收到客户端发送的用户名后,判断是否为“liu”,根据判断结果发送不同的字符串给客户端;
6. 客户端接收到服务端发送的字符串后,打印输出,并关闭连接。
阅读全文