linux编写socket程序,让客户端连接服务器并接受欢迎信息和时间
时间: 2023-06-26 09:08:02 浏览: 173
基于socket编程的客户端和服务器端程序
以下是一个简单的 Linux socket 编程示例,可以让客户端连接服务器并接收欢迎信息和时间:
服务器端代码(server.c):
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <time.h>
#define PORT 8888
#define MAXLINE 1024
int main() {
int sockfd, connfd;
char buffer[MAXLINE];
struct sockaddr_in servaddr, cliaddr;
time_t ticks;
// 创建套接字
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
// 绑定地址和端口
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
if (bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) == -1) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听连接
if (listen(sockfd, 5) == -1) {
perror("listen failed");
exit(EXIT_FAILURE);
}
printf("Server is listening on port %d...\n", PORT);
while (1) {
socklen_t clilen = sizeof(cliaddr);
connfd = accept(sockfd, (struct sockaddr *)&cliaddr, &clilen);
if (connfd == -1) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// 获取当前时间
ticks = time(NULL);
snprintf(buffer, sizeof(buffer), "Welcome to the server! The current time is %.24s\r\n", ctime(&ticks));
// 发送欢迎信息
write(connfd, buffer, strlen(buffer));
// 关闭连接
close(connfd);
}
return 0;
}
```
客户端代码(client.c):
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 8888
#define MAXLINE 1024
int main() {
int sockfd;
char buffer[MAXLINE];
struct sockaddr_in servaddr;
// 创建套接字
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
// 设置服务器地址和端口
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
// 连接服务器
if (connect(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) == -1) {
perror("connection failed");
exit(EXIT_FAILURE);
}
// 读取欢迎信息
read(sockfd, buffer, MAXLINE);
printf("%s", buffer);
// 关闭连接
close(sockfd);
return 0;
}
```
编译和运行:
```bash
# 编译服务器端
gcc -o server server.c
# 启动服务器
./server
# 编译客户端
gcc -o client client.c
# 运行客户端
./client
```
运行客户端后,应该能看到类似以下内容的输出:
```
Welcome to the server! The current time is Fri Mar 19 11:56:51 2021
```
阅读全文