2 回答
TA贡献1803条经验 获得超6个赞
应该没有关系的,
你确认下面这么做也是正常的?
//TCPSend(buf1);----------(1)
if((recvbytes=recv(client_fd,buf,100,0))==-1)
{
perror("recv 出错!");
exit(1);
}
//else
//{
//TCPSend(buf1);//-----(2)
//printf("buf1 has been sent!");
//}
TCPSend(buf1);//-----(3)
printf("buf1 has been sent!");
TA贡献1825条经验 获得超6个赞
int TCPSend(char data[])函数里面的send函数的第一个参数不是sockfd, 应该是client_fd.
sockfd一直在监听着, 所以这边用到的时候就内存错误直接退出了.
////////////////////////////////////////////////////////////////
你看下你的客户端是否有问题. (比如bind的端口号, 连接的端口号等) 我是在Ubuntu上运行的, 结果正常. 下面是我的客户端测试代码:
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
int main(void)
{
struct sockaddr_in cliaddr;
memset(&cliaddr, 0, sizeof(struct sockaddr_in));
cliaddr.sin_family = AF_INET;
cliaddr.sin_port = htons(2000);
cliaddr.sin_addr.s_addr = htons(INADDR_ANY);
memset(&cliaddr.sin_zero, 0, 8);
int sock = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == sock)
{
printf("socket error\n");
return -1;
}
int brs = bind(sock, (struct sockaddr*)&cliaddr, sizeof(struct sockaddr_in));
if(-1 == brs)
{
printf("bind error\n");
return -1;
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
inet_aton("127.0.0.1", &addr.sin_addr);
memset(&cliaddr.sin_zero, 0, 8);
int rs = connect(sock, (struct sockaddr*)&addr, sizeof(struct sockaddr_in));
if(-1 == rs)
{
printf("connect error\n");
if(errno == EAFNOSUPPORT)
{
printf("7");
}
return -1;
}
char recv_buf[100];
char buf[100];
printf("now send\n");
int rs2 = send(sock, buf, sizeof(buf), 0);
if(-1 == rs2)
{
printf("send error\n");
return -1;
}
printf("end send\n");
printf("now recv\n");
size_t num = recv(sock, recv_buf, 100, 0);
printf("end recv\n");
if(-1 == num)
{
printf("recv error\n");
if(errno = ENOMEM)
{
printf("7");
}
return -1;
}
if(0 == num)
{
printf("another recv error\n");
return -1;
}
recv_buf[num] = '\0';
printf("%s\n\n\n", recv_buf);
}
客户端运行结果是:
now send
end send
now recv
end recv
send data test!
这边还是建议每次accept后开一个线程出去send和recv
- 2 回答
- 0 关注
- 69 浏览
添加回答
举报