I have two android apps, one running in java and the other in c++. I need to connect these two apps and I have selected socket connection. I used java as a local server and c++ as a client and I got this code
Server (Java):
public void Initialization() {
int port = 8888;
try (ServerSocket serverSocket = new ServerSocket(port)) {
Log.d("ServerConnect", "The server is running and waiting for a connection on port " + port);
while (true) {
try (Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
Log.d("ServerConnect", "The client is connected: " + clientSocket.getInetAddress().getHostAddress());
String inputLine;
while ((inputLine = in.readLine()) != null) {
Log.d("ServerConnect", "Message from the client: " + inputLine);
out.println("Echo: " + inputLine);
}
} catch (IOException e) {
Log.d("ServerConnect", "Mistake when interacting with a customer: " + e.getMessage());
e.printStackTrace();
}
}
} catch (IOException e) {
Log.d("ServerConnect", "Failed to start the server: " + e.getMessage());
e.printStackTrace();
}
}
Client (C++):
int TCPClient() {
int sock = 0;
struct sockaddr_in serv_addr;
const char* message = "Hello by C++";
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
LOGW("Error creating a socket");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8888);
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
LOGW("Invalid address/ Address not supported");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
LOGW("Connection failed");
return -1;
}
if (send(sock, message, strlen(message), 0) < 0) {
LOGW("Message sending error");
close(sock);
return -1;
}
LOGW("The message has been sent");
if (recv(sock, buffer, 1024, 0) < 0) {
LOGW("Error reading a response from the server");
close(sock);
return -1;
}
LOGW("Message from the server: %s", buffer);
sleep(1);
close(sock);
return 0;
}
Judging by the logs that I get the client successfully connects to the local server, but as soon as the client sends a message to the server it seems to be blocked at some stage of sending for no known reason, respectively the server does not receive the message from the client. An interesting fact that I noticed if after connecting the client to the server to close the client application, then according to the logs the message is unblocked and still reaches the server, why does this happen? I am not new to sockets, but this is the first time I encounter such a problem.
zolotov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.