I would like to apologise for my english. It's not my native language.
I'm trying to write simple TCP server and client. I have a problem with sending a number from client to server. Here is the code from client side:
public class ConnectionHandler {
private InetAddress address;
private int port;
private Socket socket;
private DataOutputStream dos;
private DataInputStream dis;
public ConnectionHandler(String ipAddress, String port) {
try {
address = InetAddress.getByName(ipAddress);
this.port = Integer.parseInt(port);
connectionHandle();
} catch (Exception e) {
e.printStackTrace();
}
}
private void connectionHandle() {
try {
socket = new Socket(address, port);
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
getCatalogueList();
} catch (Exception e) {
e.printStackTrace();
}
private void getCatalogueList() {
try {
dos.writeInt(1);
sendFile();
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendFile() {
try{
dos.writeInt(2);
} catch(Exception e) {
e.printStackTrace();
}
}
Everything works fine when I'm sending number 1 in getCatalogueList(), but then in sendFile I'm trying to send number 2, but my server is getting 0. I've checked that if I'm sending numbers in one function:
private void getCatalogueList() {
dos.writeInt(1);
dos.writeInt(2);
}
everything works. Problem is only when I'm using two different functions.
If someone could help me how to prevent that and explain to me why this is happening I will be really grateful.
Server code (it's in C, I'm using bsd sockets)
int handleConnection(int clientSocket) {
short connectionClosed = False;
long action;
while(!connectionClosed) {
recv(clientSocket, &action, sizeof(int), 0);
action = ntohl(action);
printf("%i\n", action);
}
return 0;
}
int main() {
const int port = 8080;
const int maxConnection = 20;
int listeningSocket, clientSocket;
struct sockaddr_in server, client;
struct hostent *host;
socklen_t sin_size = sizeof(struct sockaddr_in);
char myhostname[1024];
listeningSocket = socket(PF_INET, SOCK_STREAM, 0);
gethostname(myhostname, 1023);
host = gethostbyname(myhostname);
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr = *(struct in_addr*) host->h_addr;
if (bind(listeningSocket, (struct sockaddr*) &server, sizeof(struct sockaddr)) == -1) {
return -1;
}
listen(listeningSocket, maxConnection);
while(True) {
sin_size = sizeof(struct sockaddr_in);
clientSocket = accept(listeningSocket, (struct sockaddr*) &client, &sin_size);
if(fork() == 0) {
handleConnection(clientSocket);
close(clientSocket);
exit(0);
}
else {
printf("Waiting for connection.\n");
continue;
}
}
return 0;
}