Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

sending files back and forth thru sockets  RSS feed

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I hope someone can answer this question.
I have wriiten a client program and a server program that communicate through sockets. socket.getInputStream() is chained to a buffered reader in the server so it's no problem to use readLine() to read Strings and send them back to the client who also uses readLine in a Thread to receive Strings.But what happens if I now want to send a file from the client to the server and back?. How can I do this?
Thanks in advance to anyone
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Read a line from the file and write it to the socket. Repeat until done. You will need some method to let the receiver know that you are finished sending the file. A string of 10 "|"'s or "@"'s or something else unique followed by a new line can tell the receiver that you are done sending the file.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Thomas!
And what about encapsulating the files or/and the text messages in different classes? For example an abstract class Message and then subclasses like FileMessage or SignUpMessage. FileMessage could have a byte[]arr that you would create reading from a file when you instantiate the class and before sending it throuh the ObjectStream to the server and then to the client.
Is this more efficient than reading byte by byte to the stream?
Could you send files encapsulated in that way?
/palace
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would imagine that sending a 16meg file by building a byte array probably wouldn't be the best way to handle that. However, the idea of using an ecapsulating class makes a lot of sense. Your FileMessage class could build the message and pass it as an object through the socket. Maybe a FileSocket class that builds FileSocketMessage objects and sends them. The FileSocketMessage could incorporate a byte array that includes part of the file. When it is done, it could either send a FileSocketTerminateMessage object or you could include some indicator on the FileSocketMessage that signifies the end of the message.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!