I wanted to send a part of file to server where it will be printed on server screen...however dos reads entire input...kindly suggest what i can do....is there any other way to read stream from socket into parts and copy those parts in file or print tem on screen
Server side:
/*Aim:to read file in parts...send part to server...write part in the file..*/
import java.io.*;
import java.net.*;
public class Tser {
public static void main(String a[])throws IOException{
ServerSocket sock=new ServerSocket(6000);
Socket csock=sock.accept();
DataInputStream dis=new DataInputStream(csock.getInputStream());
FileWriter fw=new FileWriter("elephant");
BufferedWriter bw=new BufferedWriter(fw);
BufferedInputStream br=new BufferedInputStream(dis);
String mess="";int c;
byte b[]=new byte[20];
while(br.read(b,0,20)!=-1)
{
for(int i=0;i<20;i++)
mess+=(char)b[i];
System.out.println(mess);
System.out.println("XX");
}
//bw.write(mess);
//System.out.print(mess);
br.close();
bw.close();
dis.close();
sock.close();
csock.close();
}
}
Client side:
import java.io.*;
import java.net.*;
public class Tcle {
public static void main(String a[])throws IOException{
Socket soc=new Socket("localhost",6000);
FileReader fr=new FileReader("samp1");
BufferedReader br=new BufferedReader(fr);
DataOutputStream dos=new DataOutputStream(soc.getOutputStream());
String hi="";int c;
char ch[]=new char[20];
while(br.read(ch,0,20)!=-1)
{
hi=String.valueOf(ch);
dos.writeBytes(hi);
//System.out.println(ch);
}
//br.flush();
fr.close();
br.close();
dos.close();
soc.close();
}}
Use
InputStream.skip()
to get to where you want to start sending.And if you're using an
InputStream
to read, you should be writing with anOutputStream
, not aReader
. Conversely, if you're using a Writer you should be reading with aReader
, but only if you know the data is text.As @EJP says, an easy way for doing it is using InputStream.skip()
The solution could be to create a new method,
Which reads buffer.length bytes at the specified
offset
frombis
So, your new
Tser
class will look likeAnd, you can do the same in the client:
In this example, we do the splitting in parts in both sides (client and server).
Let's suppose that the file
sample
contains the following characters:1.(Client side): we take 64 bytes starting at byte 2. So, we are sending:
2.(Server side): we read 20 bytes starting at byte 10. (That's it, it will be the byte 74 of the original file). So, the output will be: