#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
typedef struct sockaddr* SP;
int main(int argc,const char* argv[])
{
// 创建socket
int sockfd = socket(AF_INET,SOCK_STREAM,0);
if(0 > sockfd)
{
perror("socket");
return EXIT_FAILURE;
}
// 准备通信地址
struct sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(6666);
addr.sin_addr.s_addr = inet_addr("121.40.246.231");
socklen_t addrlen = sizeof(addr);
// 连接服务器
if(connect(sockfd,(SP)&addr,addrlen))
{
perror("connect");
return EXIT_FAILURE;
}
char buf[4096] = {};
size_t buf_size = sizeof(buf);
for(;;)
{
// 发送请求
printf(">>>");
gets(buf);
int ret = write(sockfd,buf,strlen(buf)+1);
if(0 >= ret)
{
printf("服务器正在升级,请稍候再试...\n");
break;
}
if(0 == strcmp(buf,"quit"))
{
printf("结束通信!\n");
break;
}
// 接收响应
ret = read(sockfd,buf,buf_size);
if(0 >= ret)
{
printf("服务器正在升级,请稍候再试...\n");
break;
}
printf("recv:%s bits:%d\n",buf,ret);
}
// 关闭socket
close(sockfd);
}