Linux网络编程之简单TCP客户端服务器端实现
程序员文章站
2024-03-22 19:09:22
...
下面的 代码有两个问题:
server 端code:
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
int main()
{
int listenfd = 0;
**if (listenfd = socket(AF_INET, SOCK_STREAM, 0) == -1)**
{
perror("socket error\n");
exit(1);
}
printf("creat socket success\n");
struct sockaddr_in seraddr;
memset(&seraddr, 0, sizeof(seraddr));
seraddr.sin_family = AF_INET;
seraddr.sin_port = htons(51888);
seraddr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (bind(listenfd, (struct sockaddr *)&seraddr,sizeof(seraddr)) < 0)
{
perror("bind error\n");
exit(1);
}
printf("bind success\n");
if (listen(listenfd, 50) < 0)
{
perror("listen error\n");
exit(1);
}
printf("listen success\n");
struct sockaddr_in peer_addr;
socklen_t addr_len = sizeof(peer_addr);
memset(&peer_addr, 0, sizeof(peer_addr));
int conid;
if ((conid = accept(listenfd, (struct sockaddr *)&peer_addr, &addr_len)) < 0)
{
perror("listen error\n");
exit(1);
}
printf("accept success\n");
printf("peer address is %s, port is %d\n", inet_ntoa(peer_addr.sin_addr),ntohs(peer_addr.sin_port));
char recbuf[1024];
while (1)
{
memset(recbuf, 0, sizeof(recbuf));
int ret = read(conid, recbuf, sizeof(recbuf));
if (ret == 0)
{
printf ("client has closed\n");
break;
}
printf ("receive data is %s, length is %d\n", recbuf, ret);
send(conid, recbuf, ret, 0);
printf ("send data is %s to client,length is %d\n", recbuf, ret);
}
close(listenfd);
close(conid);
return 0;
}
TCP client 端 code:
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
int main()
{
int confd = 0;
if((confd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket error\n");
exit(1);
}
printf("create socket success\n");
struct sockaddr_in seraddr;
memset(&seraddr, 0, sizeof(seraddr));
seraddr.sin_family = AF_INET;
seraddr.sin_port = htons(51888);
seraddr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(confd, (struct sockaddr *)&seraddr, sizeof(seraddr)) < 0)
{
perror("connect error\n");
exit(1);
}
printf ("connect to server success\n");
char sendbuf[1024] = {0};
char recbuf[1024] = {0};
while (fgets(sendbuf, sizeof(sendbuf), stdin) != NULL)
{
write(confd, sendbuf, strlen(sendbuf));
read(confd, recbuf, **strlen**(recbuf));
printf ("receive data:%s\n", recbuf);
memset(sendbuf, 0, sizeof(sendbuf));
memset(recbuf, 0, sizeof(recbuf));
}
close(confd);
return 0;
}
问题1:
运行 server 端应该会报下面的错误:
Socket operation on non-socket
原因是 建立socket 这句 if(listenfd = socket(AF_INET, SOCK_STREAM, 0) == -1)
等号的优先级比比较符低,所以 listenfd 永远等于 false,从而导致后面bind 了一个 非法 socket。
问题2:
调试过程中发现 Client 收不到 server发送端发送端数据。
最后调查发现是 client 端 调用 read函数时
read(confd, recbuf, strlen(recbuf));
recbuf 的string length 恒为0, 所以接收不到数据。