用c语言写一段socket程序,实现服务器和客户端TCP/IP通信,编写客户端向服务器发送"HELLO",服务器端ip地址为192.168.0.7,端口号是6000
时间: 2024-11-03 17:23:08 浏览: 5
在C语言中,我们可以使用标准库`sys/socket.h`和`netinet/in.h`来编写简单的TCP/IP服务器和客户端程序。下面是一个简化的示例,演示了如何创建一个服务器监听来自客户端的连接,并处理"HELLO"消息。
**服务器端代码(server.c)**:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 6000
#define MAX_CLIENTS 5
int main() {
int server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
char buffer[100];
// 创建服务器套接字
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
perror("Failed to create server socket");
exit(1);
}
// 设置服务器地址
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
inet_pton(AF_INET, "192.168.0.7", &server_addr.sin_addr);
// 绑定并监听
if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("Failed to bind server");
close(server_socket);
exit(1);
}
listen(server_socket, MAX_CLIENTS);
printf("Server listening on %s:%d...\n", inet_ntoa(server_addr.sin_addr), ntohs(server_addr.sin_port));
while (1) {
// 接受客户端连接
client_socket = accept(server_socket, (struct sockaddr*)&client_addr, NULL);
if (client_socket == -1) {
perror("Accept failed");
continue;
}
// 读取数据
read(client_socket, buffer, sizeof(buffer));
buffer[strcspn(buffer, "\r\n")] = '\0'; // 移除换行符
printf("Received message: %s\n", buffer);
// 发送响应
write(client_socket, "HELLO from server!\n", strlen("HELLO from server!"));
// 关闭连接
close(client_socket);
}
return 0;
}
```
**客户端代码(client.c)**:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define SERVER_IP "192.168.0.7"
#define PORT 6000
int main() {
int client_socket;
struct sockaddr_in server_addr;
char message[] = "HELLO";
// 创建客户端套接字
client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket == -1) {
perror("Failed to create client socket");
exit(1);
}
// 设置服务器地址
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
inet_aton(SERVER_IP, &server_addr.sin_addr);
// 连接到服务器
if (connect(client_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("Connect failed");
close(client_socket);
exit(1);
}
// 发送消息
send(client_socket, message, strlen(message), 0);
printf("Sent message: '%s'\n", message);
// 读取服务器响应
char response[100];
recv(client_socket, response, sizeof(response), 0);
printf("Received response: %s\n", response);
// 关闭连接
close(client_socket);
return 0;
}
```
要运行这个程序,首先编译服务器端代码然后启动服务器(`./server`),接着编译客户端代码并运行(`./client`)。客户端将连接到指定的IP和端口并向服务器发送"HELLO",服务器会回应"HELLO from server!"。
阅读全文