以下是一個簡單的C語言示例,演示了如何使用socket編程創建一個簡單的服務器和客戶端。在此示例中,服務器將偵聽來自客戶端的消息并將其原樣發送回去。
// 服務器端#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 8080
int main(int argc, char *argv[]) {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *hello = "Hello from server";
// 創建套接字文件描述符
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 設置套接字選項,允許多個連接復用同一端口
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
// 將套接字綁定到指定IP和端口
if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address))<0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 開始監聽連接請求
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
// 接受并處理客戶端連接
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen))<0) {
perror("accept");
exit(EXIT_FAILURE);
}
// 從客戶端讀取數據
valread = read( new_socket , buffer, 1024);
printf("%s\n",buffer);
// 向客戶端發送響應消息
send(new_socket , hello , strlen(hello) , 0 );
printf("Hello message sent\n");
return 0;
}
// 客戶端#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#define PORT 8080
int main(int argc, char *argv[]) {
int sock = 0, valread;
struct sockaddr_in serv_addr;
char *hello = "Hello from client";
char buffer[1024] = {0};
// 創建套接字
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// 將IPv4地址從點分十進制轉換為二進制格式
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) {
printf("\nInvalid address/ Address not supported \n");
return -1;
}
// 連接到服務器
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
return -1;
}
// 向服務器發送消息
send(sock , hello , strlen(hello) , 0 );
printf("Hello message sent\n");
// 從服務器接收響應
valread = read( sock , buffer, 1024);
printf("%s\n",buffer );
return 0;
}
要編譯和運行這兩個文件,您可以使用以下命令:
# 編譯服務器端程序gcc server.c -o server
# 編譯客戶端程序
gcc client.c -o client
# 運行服務器端程序
./server
# 在另一個終端窗口中運行客戶端程序
./client
此示例將在本地主機上創建一個簡單的TCP連接。客戶端將向服務器發送"Hello from client"消息,然后服務器將收到該消息并發送"Hello from server"。