I am trying to send byte data from client to server using sockets in Java. My idea is to upload image file from client to server. But, it was not working and hence I tried to send ASCII characters to see if they are received by server. I found out that the bytes sent from client are sometimes received fully and sometimes only part of the bytes sent is received by server. Some of the bytes sent by client are lost i.e. not received on the server. Why is that happening?
Server:
void start() {
try {
serverSocket = new ServerSocket(1024);
System.out.println("Server started...");
} catch (IOException ex) {
ex.printStackTrace();
}
}
void listen() {
try {
while (true) {
Socket socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
String line = reader.readLine();
String com[] = line.split(":");
if (com[0].equalsIgnoreCase("image")) {
String fn = com[1];
long len = Long.parseLong(com[2]);
InputStream fin = socket.getInputStream();
FileOutputStream fout = new FileOutputStream("received_" + fn);
long i = 0;
int b;
while (i < len) {
b = fin.read();
fout.write(b);
System.out.print((char)b + " " );
i++;
}
fout.close();
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
Client:
Socket socket;
void send() {
try {
socket = new Socket("localhost", 1024);
OutputStream fout = socket.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fout, "utf-8"));
writer.write("image:koala.jpg:11\r\n");
writer.flush();
int ch = 0;
byte val[] = "hello there".getBytes("utf-8");
while(ch < val.length){
fout.write(val[ch]);
ch++;
}
fout.flush();
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}