Socket Streams

C

Chase Preuninger

When I read the data off the stream it return -1.


//run method on the sending side
public void run()
{
Socket s = null;
InputStream in = null;
try
{
s = server.accept();

if(s.getInetAddress().getHostAddress().equalsIgnoreCase(validIP))
{
in = new BufferedInputStream(new
FileInputStream(from));
OutputStream out = new
BufferedOutputStream(s.getOutputStream());
for(int b = in.read(); b != -1; b = in.read())
{
out.write(b);
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
try
{
s.close();
}
catch(Exception ex){}
try
{
server.close();
}
catch(Exception ex){}
try
{
in.close();
}
catch(Exception ex){}
}
}
_____________________________________________________________________________________

//run method on receiving thread
public void run()
{
Socket s = new Socket();
OutputStream out = null;
try
{
s.connect(addr);
ProgressMonitorInputStream in = new
ProgressMonitorInputStream(parent, "Downloading " + file,
s.getInputStream());
in.getProgressMonitor().setMaximum(1000);
out = new BufferedOutputStream(new FileOutputStream(to));
int b;
int read = 0;
System.out.println(s.getPort());
System.out.println(in.read());
while(!s.isClosed() && (b = in.read()) != -1)
{
out.write(b);
read++;
double frac = (double)read / (double)size;
frac *= 1000;
in.getProgressMonitor().setProgress((int)frac);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
if(s != null && s.isConnected())
{
try
{
s.close();
}
catch(Exception ex){}
}
if(out != null)
{
try
{
out.close();
}
catch(Exception ex){}
}
}
}
 
G

Gordon Beaton

When I read the data off the stream it return -1.

The remote has closed. You are at EOF. Stop reading. Get over it.

Do not expect Socket.isClosed(), Socket.isConnected() etc to tell you
anything useful about the connection. Use the return value from read()
for that.
System.out.println(in.read());

Why do you read (and throw away) the first byte?

/gordon

--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top