#include <stdio.h> #include <string.h> #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> #include <netinet/in.h> #include <stdlib.h> #include <arpa/inet.h> #include <unistd.h> void *Writhdata(void *arge) { int ret=((void*)arge); char buf[32]={0}; while(1) { if(read(ret,buf,32)>0) { printf("buf=%s\r\n",buf); memset(buf,0,32); } } } int main(int argc,char *argv[]) { int sockfd; struct sockaddr_in cli; int port; int ret; pthread_t writethread; int running2=1; char buf[32]={0}; int str[32]={0}; sockfd =socket(AF_INET,SOCK_STREAM,0); if(sockfd==-1) { perror("socket is fail\r\n"); } port=atoi(argv[2]); cli.sin_addr.s_addr=inet_addr(argv[1]); cli.sin_family=AF_INET; cli.sin_port=htons(port); ret=connect(sockfd,(struct sockaddr *)&cli,sizeof(struct sockaddr_in)); //客户端链接服务器 if(ret==-1) { perror("connect is fail\r\n"); } pthread_create(&writethread,NULL,Writhdata,&ret); while(running2) { fgets (str,32,stdin); if(strstr(str,"exit") != NULL) { running2=0; write(ret,"c-bay!!!",9); } write(ret,buf,32); } }
时间: 2024-04-15 21:26:42 浏览: 118
这段代码是一个基于TCP的客户端程序,用于与服务器进行通信。代码中使用了线程来处理接收数据的功能。
主要的函数包括`main()`和`Writhdata()`。`main()`函数中创建了一个套接字并与服务器建立连接,然后创建了一个线程用于接收数据。之后进入一个循环,从标准输入中获取用户输入的数据,并将其发送给服务器。
`Writhdata()`函数是线程函数,负责接收服务器发送过来的数据,并打印到控制台上。
需要注意的是,代码中有一些问题,比如在`main()`函数的最后一行应该是将`str`发送给服务器而不是`buf`。另外,`fgets()`函数的第二个参数应该使用`str`而不是整型数组`str`。
此外,代码中还缺少了一些错误处理的部分,比如对`socket()`和`connect()`函数的返回值进行判断,以及线程创建失败的处理等。
如果你有具体的问题或者需要进一步解释,请告诉我。
阅读全文