error in transferring file using tcp in java -
i developing web app using jsp
in use tcp connection
send file server client. while doing so, program goes infinite loop. doesn't return anything. can please me?
i posting server , client code here.
server code:
byte[] senddata = new byte[1024]; byte[] receivedata = new byte[1024]; senddata = "file".getbytes(); datagrampacket sendpacket = new datagrampacket(senddata, senddata.length, ipaddress, 5006); clientsocket.send(sendpacket); senddata = file.getbytes(); sendpacket = new datagrampacket(senddata, senddata.length, ipaddress, 5006); clientsocket.send(sendpacket); serversocket serversocket = new serversocket(5494); socket socket = serversocket.accept(); file transferfile = new file("c:\\users\\krishna\\documents\\lanman\\" + file); byte[] bytearray = new byte[(int) transferfile.length()]; fileinputstream fin = new fileinputstream(transferfile); bufferedinputstream bin = new bufferedinputstream(fin); bin.read(bytearray, 0, bytearray.length); outputstream os = socket.getoutputstream(); os.write(bytearray, 0, bytearray.length); datagrampacket receivepacket = new datagrampacket(receivedata, receivedata.length); clientsocket.receive(receivepacket); string = (new string(receivedata, "utf-8")).trim(); //if(a.equals()) os.flush(); //bin.close(); socket.close(); serversocket.close();
client code:
if (a.startswith("file")) { byte b[] = new byte[1024]; received = new datagrampacket(receivedata, receivedata.length); serversocket.receive(received); = (new string(receivedata, "utf-8")).trim(); int filesize = 2022386; int bytesread; int currenttot = 0; socket = new socket(ip, 5494); byte[] bytearray = new byte[filesize]; inputstream = socket.getinputstream(); fileoutputstream fos = new fileoutputstream("c:\\lanman\\" + a); bufferedoutputstream bos = new bufferedoutputstream(fos); bytesread = is.read(bytearray, 0, bytearray.length); currenttot = bytesread; { bytesread = is.read(bytearray, currenttot, (bytearray.length - currenttot)); if (bytesread >= 0) currenttot += bytesread; } while (bytesread > -1); bos.write(bytearray, 0, currenttot); bos.flush(); bos.close(); //fos.close(); //is.close(); senddata = "ok".getbytes(); datagrampacket send = new datagrampacket(senddata, senddata.length, ip, port); serversocket.send(send); socket.close(); }
you implemented deadlock.
the server writes file content, wait datagram packet client, closes socket.
the client reads until server closes socket, sends datagram packet.
so each party waiting other one.
also, never ignore result of inputstream.read() method you're doing in server code. can never assume file read in 1 single call.
Comments
Post a Comment