Commit 509e1f53 authored by 马伊齐's avatar 马伊齐

初版Socket测试代码

parent 76b6f630
......@@ -7,15 +7,14 @@
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888 // 服务器端口号
#define MAXLINE 1024 // 缓冲区大小
#define PORT 8888 // 服务器端口号
#define IP "192.168.232.129"
int main(int argc, char *argv[])
{
int sockfd; // 连接套接字
struct sockaddr_in servaddr; // 服务器地址结构
char buf[MAXLINE]; // 缓冲区
char buf[BUFFER_SIZE]; // 缓冲区
int n; // 读写字节数
// 创建连接套接字,使用TCP协议
......@@ -23,10 +22,19 @@ int main(int argc, char *argv[])
sockfd = sock_init(0, servaddr.sin_addr.s_addr, PORT);
// 循环从标准输入读取数据,并发送给服务器,然后接收服务器的回复,并打印
while (fgets(buf, MAXLINE, stdin) != NULL)
while (fgets(buf, BUFFER_SIZE, stdin) != NULL)
{
if (strncmp(buf, "exit\n", 4) == 0)
{
printf("Close the connection.\n");
break;
}
printf("send: %s\n", buf);
sock_write(sockfd, buf, strlen(buf)); // 发送数据
n = sock_read(sockfd, buf, MAXLINE); // 接收数据
// 清空buf
memset(buf, 0, BUFFER_SIZE);
printf("recv: %s\n", buf);
n = sock_read(sockfd, buf, BUFFER_SIZE); // 接收数据
if (n == 0)
{
printf("the other side has been closed.\n");
......@@ -36,7 +44,7 @@ int main(int argc, char *argv[])
}
// 关闭连接套接字
close(sockfd);
sock_exit(sockfd);
return 0;
}
......@@ -17,41 +17,52 @@ int main()
char buf[BUFFER_SIZE]; // 缓冲区
char str[INET_ADDRSTRLEN]; // IP地址字符串
int n; // 读写字节数
uint32_t ipaddr, port; // 对端连接的IP地址和端口
// 创建监听套接字,使用TCP协议
inet_pton(AF_INET, INADDR_ANY, &servaddr.sin_addr);
listenfd = sock_init(1, servaddr.sin_addr.s_addr, PORT);
listenfd = sock_init(1, INADDR_ANY, PORT);
// 接受客户端连接请求,返回连接套接字
cliaddr_len = sizeof(cliaddr);
printf("waiting for client to connect...\n");
connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddr_len);
if (connfd < 0)
{
perror("accept error");
}
// 打印客户端的IP地址和端口号
printf("connected client IP: %s, port: %d\n",
inet_ntop(AF_INET, &cliaddr.sin_addr, str, sizeof(str)),
ntohs(cliaddr.sin_port));
else
{
printf("accept a new client, fd: %d\n", connfd);
}
sock_info(connfd, &ipaddr, &port);
servaddr.sin_addr.s_addr = ipaddr;
// 将获取到的字符串反转
char *p = inet_ntoa(servaddr.sin_addr);
printf("connected client IP: %s, port: %d\n", p, port);
while (1)
{
// 循环读取客户端发送的数据,并回复
int reg_success = sock_ev_register(connfd, sock_read, SOCK_READ);
if (reg_success != 0)
int n = sock_read(connfd, buf, BUFFER_SIZE);
if (n == 0)
{
printf("[%s],[%d],[%d]\n", __FILE__, __LINE__, reg_success);
perror("register fail");
return -1;
printf("The other side has been closed.\n");
break;
}
else
{
printf("received from %s at PORT %d\n",
inet_ntop(AF_INET, &cliaddr.sin_addr, str, sizeof(str)),
ntohs(cliaddr.sin_port));
printf("received: %s\n", buf);
sock_write(connfd, buf, n);
}
// 关闭连接套接字
close(connfd);
}
// 关闭监听套接字
close(listenfd);
sock_exit(connfd);
sock_exit(listenfd);
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment