我依次发送不同大小的数据包,如何以我发送的大小分别接收数据包,而不将其累积在缓冲区中。看来现在服务器将添加到缓冲区中,直到它填满为止,然后我就可以对其进行处理了。
示例:
缓冲区大小:84。
从客户端发送:84字节,76字节,76字节,80字节
在服务器中接收:84个字节,84个字节,84个字节,64个字节。
我想在发送邮件时收到它们。有可能吗?
int port = stoi(getconfig("server_port"));
std::string ipAddress = getconfig("ip_address");
// Create a socket
int listening = socket(AF_INET,SOCK_STREAM,0);
if (listening < 0){
std::cerr << "Can't create a socket!" << endl;
Logger("Can't create a socket!");
exit(-1);
}
std::cout << "The socket server was created successfully." << endl;
// Bind the socket to a IP / port
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
inet_pton(AF_INET,ipAddress.c_str(),&hint.sin_addr);
if (bind(listening,(sockaddr*)&hint,sizeof(hint)) < 0){
cerr << "Can't bind to IP/port!" << endl;
Logger("Can't bind to IP/port!");
exit(-1);
}
// Mark the socket for listening in
if (listen(listening,SOMAXCONN) < 0){
cerr << "Can't listen!" << endl;
Logger("Can't listen!");
exit(-1);
}
// accept a call
sockaddr_in client;
socklen_t clientSize = sizeof(client);
char host[NI_MAXHOST];
char svc[NI_MAXSERV];
while(true){
int clientsoket = accept(listening,(sockaddr*)&client,&clientSize);
if(clientsoket < 0){
cerr << "Problem with client connecting!" << endl;
Logger("Problem with client connecting!");
break;
}
cout << "The client whas conected successfully." << endl;
memset(host,NI_MAXHOST);
memset(svc,NI_MAXSERV);
int result = getnameinfo((sockaddr*)&client,clientSize,host,NI_MAXHOST,svc,NI_MAXSERV,0);
if(result == 0) {
cout << host << " connected on " << svc << endl;
} else {
inet_ntop(AF_INET,&client.sin_addr,NI_MAXHOST);
cout << host << " connected on " << ntohs(client.sin_port) << endl;
}
// While receiving
char buff[84];
while(true){
// Clear the buffer
memset(buff,sizeof(buff));
// Wait for a message
int bytesRecv = recv(clientsoket,buff,sizeof(buff),0);
if(bytesRecv < 0){
cerr << "There was a connection issue!" << endl;
Logger("There was a connection issue!");
break;
}
if(bytesRecv == 0){
cout << "The client disconnected." << endl;
Logger("The client disconnected");
break;
}
cout << "bytesRecv: " << bytesRecv << endl;
}
// Close the socket
close(clientsoket);
}