以下是一個簡單的示例代碼,用C語言編寫一個簡單的Socket服務器和客戶端:
服務器端代碼:
```c
#include
#include
#include
#include
#include
#include
#include
#define PORT 8888
#define BUFFER_SIZE 1024
int main() {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len = sizeof(client_addr);
char buffer[BUFFER_SIZE] = {0};
// 創建socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
// 設置服務器地址
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
// 綁定地址和端口
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 監聽連接
if (listen(server_fd, 5) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
// 接受客戶端連接
if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_len)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// 從客戶端收取數據
if (read(client_fd, buffer, BUFFER_SIZE) < 0) {
perror("read failed");
exit(EXIT_FAILURE);
}
printf("Received message: %s\n", buffer);
// 關閉連接
close(client_fd);
close(server_fd);
return 0;
}
```
客戶端代碼:
```c
#include
#include
#include
#include
#include
#include
#include
#define PORT 8888
#define SERVER_IP "127.0.0.1"
#define BUFFER_SIZE 1024
int main() {
int client_fd;
struct sockaddr_in server_addr;
char buffer[BUFFER_SIZE] = "Hello from client";
// 創建socket
if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
// 設置服務器地址
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_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("connect failed");
exit(EXIT_FAILURE);
}
// 發送數據給服務器
if (write(client_fd, buffer, strlen(buffer)) < 0) {
perror("write failed");
exit(EXIT_FAILURE);
}
// 關閉連接
close(client_fd);
return 0;
}
```
請注意,這只是一個非常簡單的示例,用于演示如何使用C語言進行基本的Socket編程。在實際應用中,您可能需要添加更多的錯誤處理和安全性檢查。