我在使用connect()和read()函数的简单TCP套接字时遇到问题。如果我先启动服务器,然后启动客户机,这个程序就会工作。但是,当我首先启动客户机时,它会继续尝试连接到服务器,然后当我启动服务器时,它会连接,但随后的读取会返回0字节。这意味着服务器关闭了套接字,但调试语句不支持这一点。
我尝试让客户机不断尝试连接到6380端口上的服务器,然后读取数据。如果连接断开,客户端将再次尝试重新连接。我已经为插座设置了这样的地址。还有什么我不知道的吗?
服务器的源代码
//***** SERVER *****
#include <iostream>
#include "SocketAdapter.h"
#include "SocketServer.h"
#include <errno.h>
#include <string.h>
unsigned char buffer[] = "123123123";
int main()
{
SocketAdapter socket;
SocketServer server(6380);
server.Start();
std::cout << "Wait for Connection" << std::endl;
server.WaitForConnection(socket);
std::cout << "Start to Send Data" << std::endl;
while(1)
{
std::cout << "Sending Data ";
int bytesSent = socket.Send(buffer, 10);
std::cout << "byteSent = " << bytesSent << std::endl;
if (bytesSent == -1)
{
std::cout << "Errno (" << errno << ") - " << strerror(errno) << std::endl;
}
sleep(1);
}//end while
std::cout << "Ending Server" << std::endl;
socket.Close();
return 0;
}
客户端的源代码
// ***** SIMPLE CLIENT ******
#include <iostream>
#include "SocketAdapter.h"
#include "SocketClient.h"
#include <string.h>
#include <errno.h>
int main()
{
SocketAdapter socket;
SocketClient client(6380, "127.0.0.1");
unsigned char buffer[1024];
while(1)
{
client.Start();
//Loop till we connect to Server
while( !client.Connect(socket) )
{
std::cout << "Trying to connect to server." << std::endl;
sleep(1);
}
std::cout << "Connected to Server" << std::endl;
//Read till we get a timeout
while(1)
{
int bytesRead = socket.Recv(buffer, 10,2000);
if (bytesRead != 10)
{
std::cout << " Failed to Read" << std::endl;
std::cout << " bytesRead = " << bytesRead << std::endl;
std::cout << " Errno (" << errno << ") - "
<< strerror(errno) << std::endl;
break;
}
std::cout << "buffer = " << buffer << std::endl;
usleep(250000);
}
std::cout << "Something went wrong, restart" << std::endl;
}
return 0;
}
./Server
Wait for Connection
Start to Send Data
Sending Data byteSent = 10
./Client
Trying to connect to server.
Trying to connect to server.
Connected to Server
Failed to Read
bytesRead = 0
Errno (107) - Transport endpoint is not connected
Something went wrong, restart
Close Socket
Close Socket File Descriptor
Connected to Server
Trying to Recv on a closed socket
Return Value = -1
Errno = Connection reset by peer
Failed to Read
bytesRead = -3
Errno (104) - Connection reset by peer
Something went wrong, restart
Close Socket
Close Socket File Descriptor
Socket cannot shutdown!
Return Value = -1
Errno = Transport endpoint is not connected
Trying to connect to server.
Close Socket
Close Socket File Descriptor
Socket cannot shutdown!
Return Value = -1
Errno = Transport endpoint is not connected