Sending and splitting an image file over tcp socket.
I am trying to write a server and client, where the server has an image file (hardcoded name), that is to be split into 512 byte packets and sent to a client who responds to each packet with an "ACK" message. The client is supposed to assemble these packets into an image file. Currently the code I have is giving problems, I don't now how to modify it.
The size of the image is 3092 bytes meaning the server should send about 6 packets and print "ack received" if the packet was received and acknowledged by the client, but it seems to only be printing it twice.
server code contains
Code:
public static void main(String[] args) throws Exception
{
ServerSocket inSocket = new ServerSocket(40075);
System.out.println("made socket");
String clientSentence;
while(true)
{
Socket sSocket = inSocket.accept();
System.out.println("accepted socket");
BufferedReader fromclient = new BufferedReader(new InputStreamReader(sSocket.getInputStream()));
DataOutputStream toClient = new DataOutputStream(sSocket.getOutputStream());
clientSentence = fromclient.readLine();
System.out.println(clientSentence);
File jfile = new File("base.jpg");
if (!jfile.exists() || !jfile.isFile())
{
System.out.println("Not a file");
}
else System.out.println("Is a file");
int filesize = (int)jfile.length();
int left = filesize;
int byteposition = 0;
System.out.println(filesize);
DataInputStream fis = new DataInputStream(new FileInputStream(jfile));
byte[] buffer = new byte[filesize];
while(left > 512)
{
try {
while(fis.read(buffer)!=-1)
{
toClient.write(buffer, byteposition, 512);
}
System.out.println("After writing");
clientSentence = fromclient.readLine();
if (clientSentence.equals("ACK"));
System.out.println("ack received");
}
catch (Exception e){}
byteposition = byteposition + 512;
left = left - 512;
}
}
}
client code contains
Code:
System.out.println("pre server socket");
Socket clSocket = new Socket(addr,40075);
System.out.println("post server socket");
DataOutputStream toPserver = new DataOutputStream(clSocket.getOutputStream());
DataInputStream fromPserver = new DataInputStream(clSocket.getInputStream());
toPserver.writeBytes(filereq);
String pReply = fromPserver.readLine();
System.out.println(pReply);
File dlfile = new File("new"+name);
dlfile.createNewFile();
int gotbytes = 0;
DataOutputStream dos = new DataOutputStream(new FileOutputStream(dlfile));
while(gotbytes < 3092)
{
try
{
while(fromPserver.available() > 0)
{
dos.writeByte(fromPserver.readByte());
gotbytes = gotbytes + 1;
}
}
catch (Exception e){}
toPserver.writeBytes("ACK");
}
System.out.println(gotbytes);
clSocket.close();
}