1
0

[Test] still not working sad

This commit is contained in:
Tony Yang 2021-12-28 01:46:48 +08:00
parent 97dae6fe69
commit 011c463ea9
Signed by: t510599
GPG Key ID: D88388851C28715D
2 changed files with 17 additions and 13 deletions

View File

@ -22,15 +22,15 @@ using namespace std;
int sockfd = 0;
void clean_up(int signum) {
int truthy = 1;
if (sockfd == -1) exit(1);
int truthy = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &truthy, sizeof(int));
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &truthy, sizeof(int));
shutdown(sockfd, SHUT_RDWR);
close(sockfd);
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &truthy, sizeof(int));
setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &truthy, sizeof(int));
exit(0);
}
@ -55,6 +55,8 @@ int main(int argc, char const *argv[]) {
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
cerr << "Failed to create socket." << endl;
clean_up(0);
exit(errno);
}
// setup server info
@ -66,8 +68,8 @@ int main(int argc, char const *argv[]) {
// use static client port
if (bind(sockfd, (struct sockaddr *) &client_info, sizeof(client_info)) == -1) {
cerr << "socket bind error" << endl;
close(sockfd);
return BINDERR_RET;
// close(sockfd);
exit(errno);
}
// setup server info
@ -78,7 +80,7 @@ int main(int argc, char const *argv[]) {
if (connect(sockfd, (struct sockaddr *) &info, sizeof(info)) == -1) {
cerr << "Connection failed." << endl;
close(sockfd);
// close(sockfd);
exit(errno);
}
@ -101,7 +103,8 @@ int main(int argc, char const *argv[]) {
if (send(sockfd, msg, sizeof(msg), 0) == -1) {
cerr << "Send error" << endl;
break;
clean_up(0);
exit(errno);
};
// receive server response
@ -140,5 +143,6 @@ int main(int argc, char const *argv[]) {
cout << endl;
}
close(sockfd);
return 0;
}

View File

@ -14,8 +14,6 @@
#define BUFFER_SIZE 256
#define NOPORT_RET 10
#define INVALID_PORT_RET 20
#define BINDERR_RET 30
#define LISTENERR_RET 35
using namespace std;
@ -99,6 +97,7 @@ int main(int argc, char const *argv[]) {
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
cerr << "Failed to create socket" << endl;
exit(errno);
}
// setup server info
@ -111,13 +110,14 @@ int main(int argc, char const *argv[]) {
if (bind(sockfd, (struct sockaddr *) &server_info, sizeof(server_info)) == -1) {
cerr << "Cannot bind socker." << endl;
close(sockfd);
return BINDERR_RET;
exit(errno);
}
// only one connection at the same time
if (listen(sockfd, 1) == -1) {
cerr << "Cannot listen to socket." << endl;
return LISTENERR_RET;
close(sockfd);
exit(errno);
}
cout << "Server up. Waiting connection..." << endl;
@ -152,7 +152,7 @@ int main(int argc, char const *argv[]) {
if (recv(client_sockfd, buffer, sizeof(buffer), 0) <= 0) {
// closed connection
cout << "Disconnected." << endl;
cout << shutdown(client_sockfd, SHUT_RDWR) << endl;
shutdown(client_sockfd, SHUT_RDWR);
close(client_sockfd);
break;
}