gpt4 book ai didi

c++ socket read()有时在连接到服务器时返回-1

转载 作者:太空宇宙 更新时间:2023-11-04 12:33:36 24 4
gpt4 key购买 nike

我是 c++ 的新手,我正在进行套接字编程,同时从服务器向客户端发送数据,read() 函数有时会返回 -1,有时会返回 64,并且工作正常。我在下面附上了我的代码,请给我一个更好的解决方案。

服务器.cpp

  if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
logger("socket failed");
exit(EXIT_FAILURE);
}

// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
logger("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_addr.s_addr = inet_addr("192.168.0.4");
address.sin_port = htons( PORT );


// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address))<0)
{
logger("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0)
{
logger("listen");
exit(EXIT_FAILURE);
}

while (true)
{
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
logger("socket not accept");
exit(EXIT_FAILURE);
}
//valread = read( new_socket , buffer, 1024);
//printf("%s\n",buffer );
send(new_socket , hash_key , strlen(hash_key) , 0 );
//printf("Hello message sent\n");
}
return 0;

客户端.cpp

                 arg |= O_NONBLOCK;
if( fcntl(sock, F_SETFL, arg) < 0) {
fprintf(stderr, "Error fcntl(..., F_SETFL) (%s)\n", strerror(errno));
exit(0);
}
int res;
res = connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
if (res < 0) {
if (errno == EINPROGRESS) {
fprintf(stderr, "EINPROGRESS in connect() - selecting\n");
do {
tv.tv_sec = 50;
tv.tv_usec = 0;
FD_ZERO(&myset);
FD_SET(sock, &myset);
res = select(sock+1, NULL, &myset, NULL, &tv);
if (res < 0 && errno != EINTR) {
fprintf(stderr, "Error connecting %d - %s\n", errno, strerror(errno));
exit(0);
}
else if (res > 0) {
// Socket selected for write
lon = sizeof(int);
if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)(&valopt), &lon) < 0) {
fprintf(stderr, "Error in getsockopt() %d - %s\n", errno, strerror(errno));
exit(0);
}
// Check the value returned...
if (valopt) {
fprintf(stderr, "Error in delayed connection() %d - %s\n", valopt, strerror(valopt)
);
exit(0);
}
break;
}
else {
fprintf(stderr, "Timeout in select() - Cancelling!\n");
exit(0);
}
} while (1);
}
else {
fprintf(stderr, "Error connecting %d - %s\n", errno, strerror(errno));
exit(0);
}
valread = read( sock , buffer, 1024);
cout<<valread<<endl;

最佳答案

您监听来自客户端的传入连接,并在服务器端的同一循环中将数据发送到客户端。您应该使用线程将它们分开。您的服务器代码在接受例程中阻塞。

关于c++ socket read()有时在连接到服务器时返回-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57430166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com