I'm trying to send and read the reply from the socket with no luck. What I got so far is, connected to the server and read connection reply (header from Ericsson telco exchange) and printed it on System.out. What I need to be able to do is send a command to the exchange and get the reply and that's where I'm stuck. Below is my test code.
Any help is appreciated.
public class ExchangeClientSocket {
public void run() {
try {
int serverPort = 23;
InetAddress host = InetAddress.getByName("my.host.ip.address");
Socket socket = new Socket(host, serverPort);
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(isr);
int i;
StringBuffer buffer = new StringBuffer();
while (true) {
i = in.read();
if (i == 60) {
break;
} else {
buffer.append((char) i);
}
}
// this returns the head from exchange
System.out.println(buffer.toString());
out.write("allip;"); // command I want to send to exchange
out.flush();
System.out.println(in.ready()); // this returns false
System.out.println(in.read());
System.out.println("damn..");
buffer = new StringBuffer();
// can't get into this loop
// this is where I want to read the allip response
while ((i = in.read()) != -1) {
i = in.read();
if (i == 60) {
break;
} else {
buffer.append((char) i);
}
}
System.out.println(buffer.toString());
out.close();
in.close();
socket.close();
} catch (UnknownHostException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is a suggestion on how to get input from the server after writing to the output stream: simply get another input stream from the socket.
So instead of reading from the same stream you create a new stream from the socket after you sent the command and read it.
I would therefore suggest to change your code to this here:
public void run() {
try {
int serverPort = 23;
InetAddress host = InetAddress.getByName("my.host.ip.address");
Socket socket = new Socket(host, serverPort);
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(isr);
int i;
StringBuffer buffer = new StringBuffer();
while (true) {
i = in.read();
if (i == 60) {
break;
} else {
buffer.append((char) i);
}
}
// this returns the head from exchange
System.out.println(buffer.toString());
out.write("allip;"); // command I want to send to exchange
out.flush();
// Create a new input stream here !!!
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
buffer = new StringBuffer();
// can't get into this loop
while ((i = in.read()) != -1) {
i = in.read();
if (i == 60) {
break;
} else {
buffer.append((char) i);
}
}
System.out.println(buffer.toString());
out.close();
in.close();
socket.close();
} catch (UnknownHostException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Related
i'm working on an instant messaging project which it's client side is android and server is java
i need to use socket with streams
here is my protocol (something like HTTP) :
Method : attachment \n
Content-Length : {some-int-value} \n
\r\n
binary data bla bla bla...
lets assume i want to send this message from client to server
by doing so exchanging header section goes pretty well
but reading binary data at the server side never complete and server goes into hang for good
Client side code :
Socket socket = new Socket();
SocketAddress address = new InetSocketAddress(SERVER_ADDRESS, SERVER_PORT);
try {
socket.connect(address);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
byte[] data = getSomeBinaryData();
writer.write("Method : attachment" + "\n");
writer.write("Content-Length : " + data.length + "\n");
writer.write("\r\n");
writer.flush();
out.write(data); // write binary data
// do more exchange later
} catch (IOException ex) {
// handle exception
}
Server starter code :
public static void main(String[] args){
ExecutorService pool = Executors.newFixedThreadPool(50);
try (ServerSocket server = new ServerSocket(PORT_NUMBER)) {
while (true) {
try {
Socket connection = server.accept();
Callable<Void> task = new ClientTask(connection);
pool.submit(task);
} catch (IOException ex) {}
}
} catch (IOException ex) {
System.err.println("Couldn't start server");
}
}
Server Task thread for each client :
class ClientTask implements Callable<Void> {
private Socket connection;
private HashMap<String, String> header = new HashMap<>();
private byte[] content;
ClientTask(Socket c) {
this.connection = c;
}
#Override
public Void call() throws Exception {
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
readHeader(reader);
System.out.println("incoming message : " + header.get("Method"));
int contentLength = Integer.parseInt(header.get("Content-Length"));
content = new byte[contentLength];
int bytesRead = in.read(content, 0, contentLength);
System.out.print(bytesRead);
return null;
}
private void readHeader(BufferedReader reader){
try {
char c;
StringBuilder builder = new StringBuilder();
while ((c = (char) reader.read()) != '\r'){
if(c == '\n'){
String line = builder.toString();
line = line.replaceAll(" ", "");
String[] sections = line.split(":");
header.put(sections[0], sections[1]);
builder = new StringBuilder(); // clear builder
}else {
builder.append(c);
}
}
reader.read(); // skip the last \n character after header
} catch (IOException e) {
e.printStackTrace();
}
}
As James said a clue I wanted to share the solution
maybe it help someone with similar issue
in the call method of ClientTask class i should use this code :
#Override
public Void call() throws Exception {
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
readHeader(reader);
System.out.println("incoming message : " + header.get("Method"));
// read binary Content
int bytesRead = 0;
int bytesToRead = Integer.parseInt(header.get("Content-Length"));
content = new byte[bytesToRead];
while (bytesRead < bytesToRead) {
int result = in.read(content, bytesRead, bytesToRead - bytesRead);
if (result == -1)
break; // end of stream
bytesRead += result;
}
return null;
}
I want to receive text files through a socket connection in java, I set up the server end but before I continue with the client I would like to know if the code I made works, except I have no idea how to test this.
Any help would be much appreciated..
EDIT: I know the port is open and listening for requests, what i want is to test what happens if it receives anything, will it create a file from the input and can I test this by simulation(sending a file or bytes i dont know)?
public class Server {
private static int port = 8080;
private static int maxConnections = 100000;
// Listen for incoming connections and handle them
public static void startServer() {
int i = 0;
try {
ServerSocket listener = new ServerSocket(port);
Socket server;
System.out.println("Started server on port:" + port);
while ((i++ < maxConnections) || (maxConnections == 0)) {
RunServer connection;
server = listener.accept();
RunServer conn_c = new RunServer(server);
Thread t = new Thread(conn_c);
t.start();
System.out.println("Created new thread");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class RunServer implements Runnable {
private Socket server;
RunServer(Socket server) {
this.server = server;
}
public void run() {
int bytesRead;
int current = 0;
BufferedOutputStream bufferedOutputStream = null;
FileOutputStream fileOutputStream = null;
DataInputStream clientData = null;
File file = null;
try {
// creating connection.
System.out.println("connected.");
// receive file
byte[] byteArray = new byte[6022386];
System.out.println("Please wait downloading file");
// reading file from socket
InputStream inputStream = server.getInputStream();
file = new File("toread.txt");
clientData = new DataInputStream(inputStream);
fileOutputStream = new FileOutputStream(file);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bytesRead = inputStream.read(byteArray, 0, byteArray.length);
current = bytesRead;
do {
bytesRead = inputStream.read(byteArray, current, (byteArray.length - current));
if (bytesRead >= 0)
current += bytesRead;
} while (bytesRead > -1);
bufferedOutputStream.write(byteArray, 0, current);
bufferedOutputStream.flush();
ReaderHelper.readTextFile(file);
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null)
fileOutputStream.close();
if (bufferedOutputStream != null)
bufferedOutputStream.close();
if (clientData != null)
clientData.close();
if (server != null)
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Well, your socket will be up on port 8080 right?
You can open your browser and type: http://localhost:8080. The browser will create a connection and the line
server = listener.accept();
will "unlock". If you just wanna test if the socket is listenning it will do. Reading the stream you will see the first message of the HTTP protocol.
At first you have a possible error in a reading loop
byte[] byteArray = new byte[6022386];
//some code
do {
bytesRead = inputStream.read(byteArray, current, (byteArray.length - current));
if (bytesRead >= 0)
current += bytesRead;
} while (bytesRead > -1);
If file length is more than byteArray.length which is possible, then (byteArray.length - current) would be negative.
I suggest you to use smaller array, e.g. byte[] byteArray = new byte[8192]; and read file like this
while ((bytesRead = in.read(byteArray)) > 0 ) {
current += bytesRead;
bufferedOutputStream.write(byteArray, 0, bytesRead);
}
storing it into disk chunk by chunk. And after exiting while loop current will hold total number of read bytes.
Send file from another thread, which will connect to server
Socket clientSocket = new Socket("localhost", Server.port);
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream());
FileInputStream fileInput = new FileInputStream("fileName");
byte[] buffer = new byte[8192];
while(fileInput.read(buffer) != -1){
output.write(buffer, 0, length);
}
//close resources
I am sending lines through a socket from a client in C, and reading on a server in Java. The best I can manage is that the client send the multiple lines, and when I close the client the server prints all the data in one line. Or to make it that one send then receives, etc. My desire is that the C application sends "Hi" in a loop, and the Java files catches first hi, prints and then catches second and prints. Right now it prints "HiHiHiHi...", but only when the connection is terminated.
I am using oracle socket example as guideline and using another guide for the C client
So reading the socket in Java is:
try {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
System.out.println("Connected with client");
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("RECEIVING " + inputLine);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
} catch (IOException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
}
Trying to write to the socket in a while loop the same string in C:
void connection(void) {
int sockfd, portno;
struct sockaddr_in serv_addr;
struct hostent *server;
/* Set time limit. */
timeout.tv_sec = 0;
timeout.tv_usec = 10;
portno = 4444;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname("Localhost");
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
while(1) {
/* Create a descriptor set containing our two sockets. */
FD_ZERO(&fds);
FD_SET(sockfd, &fds);
rc = select(sizeof(fds)*8, &fds, NULL, NULL, &timeout);
if (rc==-1) {
perror("select failed");
}
bzero(buffer,256);
char *buffer2 = "here";
n = write(sockfd,buffer2,strlen(buffer2));
if (n < 0)
error("ERROR writing to socket");
}
}
Your server is waiting for a \n before it prints anything.
Your client isn't sending any \n chars.
You might try:
char *buffer2 = "here"\n;
What type of stream can I use to send a request message over a tcp socket to jabber.
I'm writing a string with xml format.
I cant use any libraries. It has to be pure java sockets.
the following is the code which i used. But the response for the second xml request is null
try {
Socket s = new Socket("195.211.49.6", 5222);
PrintWriter out = new PrintWriter(s.getOutputStream());
out.println("<stream:stream to='nimbuzz.com' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>");
out.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(s
.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
out.println("<iq type='set' xml:lang='en' id='terms' to='nimbuzz.com'><query xmlns='jabber:iq:auth'><username>username</username><password>password</password><resource>resource</resource></query></iq>");
out.flush();
reader = new BufferedReader(new InputStreamReader(s
.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
s.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
this is what i have implemented in c#, it works quite fast too.
Socket m_socWorker;
try
{
m_socWorker = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
string ipString = "195.211.49.6";
string str2 = "5222";
int port = Convert.ToInt16(str2, 10);
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(ipString), port);
m_socWorker.Connect(remoteEP);
string page=string.Empty, page1=string.Empty, page2=string.Empty;
string s = "<stream:stream to='nimbuzz.com' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>";
byte[] bytes = Encoding.UTF8.GetBytes(s);
byte[] buffer = new byte[0x4b38];
m_socWorker.Send(bytes, bytes.Length, SocketFlags.None);
int count = 0;
count = m_socWorker.Receive(buffer, buffer.Length, SocketFlags.None);
page = page + Encoding.ASCII.GetString(buffer, 0, count);
byte[] buffer3 = new byte[0x4b38];
int num2 = 0;
num2 = m_socWorker.Receive(buffer3, buffer3.Length, SocketFlags.None);
page1 = page1 + Encoding.ASCII.GetString(buffer3, 0, num2);
if (page1.Replace("\"", "'").IndexOf("<stream:features><starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/><mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><mechanism>PLAIN</mechanism><mechanism>PLAIN TEXT</mechanism></mechanisms><register xmlns='http://jabber.org/features/iq-register'/></stream:features>", 0) != 0)
{
string str3 = "<iq type='set' xml:lang='en' id='Nimbuzz_Login' to='nimbuzz.com'><query xmlns='jabber:iq:auth'><username>username</username><password>password</password><resource>resource</resource></query></iq>";
byte[] buffer4 = new byte[0x30d40];
buffer4 = Encoding.UTF8.GetBytes(str3);
byte[] buffer5 = new byte[0x4b38];
m_socWorker.Send(buffer4, buffer4.Length, SocketFlags.None);
int num3 = 0;
num3 = m_socWorker.Receive(buffer5, buffer5.Length, SocketFlags.None);
page2 = Encoding.ASCII.GetString(buffer5, 0, num3);
string str4 = page2.Replace("\"", "'");
int num4 = 1;
}
}
catch (SocketException)
{
}
catch (Exception)
{
}
You are attaching a 2nd BufferedReader (InputStreamReader (...)) to your stream.
Probably the answer to your second request is being consumed and lost in the first buffer.
Try re-using your initial BufferedReader reader; to read the answer to the second message. Remember that XMPP is a single bi-directional stream, so all interaction happens through the same socket throughout the lifetime of your connection.
-- EDIT --
Q: How should the second request be like?
A: Editing your code to give you a starting point (not checked for compilation, just to give you the idea on how to proceed):
private static final int BUFFER_SIZE = 1024;
// Encapsulate the read process
private String readData(Reader reader) throws IOException {
StringBuilder result = new StringBuilder();
char[] buffer = new char[BUFFER_SIZE]; // [note1]
while (reader.ready()) { // [note2]
int charsRead = reader.read(buffer,0,BUFFER_SIZE-1));
if (charsRead > 0) {
result.append(buffer,0,charsRead);
}
}
return result.toString();
}
public void readStuff() {
try {
Socket s = new Socket("195.211.49.6", 5222);
PrintWriter out = new PrintWriter(s.getOutputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(s.getInputStream()));
out.println("<stream:stream to='nimbuzz.com' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>");
out.flush();
// Read out the data and print it to the console
System.out.println(readData(bufferedReader));
// Second request over the same socket
out.println("<iq type='set' xml:lang='en' id='terms' to='nimbuzz.com'><query xmlns='jabber:iq:auth'><username>username</username><password>password</password><resource>resource</resource></query></iq>");
out.flush();
// Read out the answer for the second result
System.out.println(readData(bufferedReader));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
Notes:
[1] This buffer can be reused across different requests. There's no actual need to recreate it every time this method is called. I left it there to provide you some anchoring with your C# code.
[2] You are checking for EOF in your code. This will potentially not happen in an XMPP connection. It's better to read the characters that are available in the stream until there're no more. Therefore I'm checking on reader.ready() instead of reader.read(...)>-1
See this question for further discussion on EOF: How do I recognize EOF in Java Sockets?
Some bytes are missing when I'm sending files over TCP connection. Though there are times that file transfer is complete.
Sending side:
class SendFile extends Thread {
Socket s;
String toIP;
String fileName;
PrintWriter pw;
BufferedReader br;
String fromIP;
String nextHopIP;
String transferTime;
int routingIndex;
final int bufferSize = 65536;
int readFile;
byte[] buffer;
FileInputStream fileIn;
OutputStream fileOut;
long fileTransferTime;
SendFile(String toIP, String fileName) {
this.toIP = toIP;
this.fileName = fileName;
}
public void run() {
while (true) {
try {
fromIP = InetAddress.getLocalHost().getHostAddress();
nextHopIP = Tables.checkRoutingTable(toIP);
if (nextHopIP.equals("none")) {
System.out.println("Invalid IP address");
} else {
s = new Socket(nextHopIP, 3434);
fileIn = new FileInputStream(fileName);
fileOut = s.getOutputStream();
buffer = new byte[bufferSize];
pw = new PrintWriter(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw.println(fromIP);
pw.println(toIP);
pw.println(fileName.split("\\\\")[fileName.split("\\\\").length - 1]);
pw.flush();
//Send file
fileTransferTime = System.currentTimeMillis();
int sum = 0;
while ((readFile = fileIn.read(buffer)) != -1) {
fileOut.write(buffer, 0, readFile);
sum += readFile;
}
System.out.println(sum);
fileIn.close();
s.shutdownOutput();
br.readLine();
fileTransferTime = System.currentTimeMillis() - fileTransferTime;
System.out.println("File transfer time: " + fileTransferTime + " ms");
s.close();
break;
}
} catch (IOException ex) {
//Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Connection timed out. Retrying...");
}
}
}
}
Receiving side:
class FileTransferThread extends Thread {
Socket fromSocket;
Socket toSocket;
String ip;
BufferedReader fromBR;
BufferedReader toBR;
PrintWriter fromPW;
PrintWriter toPW;
String[][] delta;
String token;
String toIP;
String fromIP;
String nextHopIP;
String absoluteFileName;
String fileName;
int deltaCount;
int entryCount;
int socketIndex;
int i;
int j;
int readFile;
final int bufferSize = 65536;
byte[] buffer;
InputStream fileIn;
FileOutputStream fileOut;
OutputStream fileHopOut;
File directory;
long fileTransferTime;
FileTransferThread(Socket s) {
this.fromSocket = s;
}
public void run() {
try {
ip = InetAddress.getLocalHost().getHostAddress();
fromBR = new BufferedReader(new InputStreamReader(fromSocket.getInputStream()));
fromPW = new PrintWriter(fromSocket.getOutputStream());
fromIP = fromBR.readLine();
toIP = fromBR.readLine();
nextHopIP = Tables.checkRoutingTable(toIP);
buffer = new byte[bufferSize];
fileIn = fromSocket.getInputStream();
fileName = fromBR.readLine();
if (!fileName.equals("\\send")) {
directory = new File("c:\\" + fromIP);
directory.mkdirs();
absoluteFileName = "c:\\" + fromIP + "\\" + fileName;
fileOut = new FileOutputStream(absoluteFileName);
while (true) {
try {
//if not yet the destination IP, pass to next hop
if (!toIP.equals(ip)) {
toSocket = new Socket(toIP, 3434);
fileHopOut = toSocket.getOutputStream();
toBR = new BufferedReader(new InputStreamReader(toSocket.getInputStream()));
toPW = new PrintWriter(toSocket.getOutputStream());
toPW.println(fromIP);
toPW.println(toIP);
toPW.println(fileName);
toPW.flush();
//Send file
while ((readFile = fileIn.read(buffer)) != -1) {
fileHopOut.write(buffer, 0, readFile);
}
toSocket.shutdownOutput();
fromPW.println(toBR.readLine());
fromPW.flush();
toSocket.close();
} else {
int sum = 0;
while ((readFile = fileIn.read(buffer)) != -1) {
fileOut.write(buffer, 0, readFile);
sum += readFile;
}
System.out.println(sum);
fileOut.flush();
fileOut.close();
fromPW.println("1");
fromPW.flush();
}
fromSocket.close();
break;
} catch (IOException ex) {
//Logger.getLogger(FileTransferThread.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Connection timed out. Retrying...");
}
}
} else {
while(true) {
try {
//if not yet the destination IP, pass to next hop
if (!toIP.equals(ip)) {
toSocket = new Socket(toIP, 3434);
fileHopOut = toSocket.getOutputStream();
toBR = new BufferedReader(new InputStreamReader(toSocket.getInputStream()));
toPW = new PrintWriter(toSocket.getOutputStream());
toPW.println(fromIP);
toPW.println(toIP);
toPW.println(fileName);
toPW.flush();
//Send file
while ((readFile = fileIn.read(buffer)) != -1) {
fileHopOut.write(buffer, 0, readFile);
}
toSocket.shutdownOutput();
fromPW.println(toBR.readLine());
fromPW.flush();
toSocket.close();
} else {
while ((readFile = fileIn.read(buffer)) != -1) {
}
fromPW.println("1");
fromPW.flush();
}
fromSocket.close();
break;
}
catch (IOException ex) {
//Logger.getLogger(FileTransferThread.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Connection timed out. Retrying...");
}
}
}
fromSocket.close();
} catch (IOException ex) {
Logger.getLogger(FileTransferThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
You are not closing - and hence not flushing - the SocketOutputStream called fileout. (You really should consider less misleading names ...).
Hm ... it appears shutdownOutput does that; its javadoc writes:
Disables the output stream for this socket.
For a TCP socket, any previously written data will be sent
followed by TCP's normal connection termination sequence.
If you write to a socket output stream after invoking
shutdownOutput() on the socket, the stream will throw
an IOException.
I leave this in case anybody else has the same idea.
Note that socket.getInputStream specifies the sorts of data loss that can happen using that facility. In particular:
The network software may discard bytes
that are buffered by the socket.
Found the error. It seems that BufferedReader is getting a chunk of data which is supposed to be for the file.