我已经制作了一个简单的服务器,当收到消息时,该服务器将打印到终端。我做的客户端只是发送消息(没有收到)当我telnet并向服务器发送消息它工作得很好并打印我发送的确切内容。但是,当我写下它下面的C客户端代码时,好像什么都没发送一样。
这是我下面代码的编译输出-wall -wextra -pedantic
./client.c: In function ‘main’:
./client.c:17:4: warning: implicit declaration of function ‘bzero’ [-Wimplicit-function-declaration]
./client.c:19:4: warning: implicit declaration of function ‘inet_addr’ [-Wimplicit-function-declaration]
./client.c:28:2: warning: implicit declaration of function ‘strlen’ [-Wimplicit-function-declaration]
./client.c:28:41: warning: incompatible implicit declaration of built-in function ‘strlen’ [enabled by default]
./client.c:22:8: warning: unused variable ‘val’ [-Wunused-variable]
./client.c:10:15: warning: unused variable ‘n’ [-Wunused-variable]
./client.c:8:14: warning: unused parameter ‘argc’ [-Wunused-parameter]
./client.c:8:26: warning: unused parameter ‘argv’ [-Wunused-parameter]
soup@soup-XPS-8300:/home/c_dev/p2pcrypt_server/v0.1.0/src/tool_tests/libev
-
/* Sample TCP client */
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
int main(int argc, char**argv)
{
int sockfd,n;
struct sockaddr_in servaddr;
char * sendline;
sendline = "hello";
sockfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
servaddr.sin_port=htons(8018);
int connect_status = connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
printf("%d\n", connect_status);
int send_status = send(sockfd,sendline,strlen(sendline),0);
printf("%d\n", send_status);
printf("END\n");
return 0;
}
更新了代码 Connect返回“0”(成功)并发送返回“5”(我认为它发送了多少个成功字符)
答案 0 :(得分:0)
这是我最终成功运行的代码,似乎需要\ r \ n和所有指出的好建议。谢谢伙伴们!
/* Sample TCP client */
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
int main(int argc, char**argv)
{
int sockfd,n;
struct sockaddr_in servaddr;
char * sendline;
sendline = "hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellolohellohellohellohellohellohellohellohellohellolohellohellohellohellohellohellohellohellohellolohellohellohellohellohellohellohellohellohellolo\r\n";
sockfd=socket(AF_INET,SOCK_STREAM,0);
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
servaddr.sin_port=htons(8018);
int connect_status = connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
printf("%d\n", connect_status);
int send_status = send(sockfd,sendline,strlen(sendline),0);
printf("%d\n", send_status);
printf("END\n");
return 0;
}