In the network programming in the TCP transmission, get the socket source, how to read and write operations, the following I listed two methods, I hope you help to add
1. Read and write using a byte array as a buffer
1 //get the socket stream and upload the image to the server2FileInputStream fis=NewFileInputStream ("C:\\12.jpg");3 4 //gets the output stream5OutputStream out=S.getoutputstream ();6 7 //using arrays as buffers8 byte[]buf=New byte[1024];9 Ten //Len is used to record length One intLen=0; A - //cyclic reading and writing - while((Len=fis.read (BUF))!=-1){ the //when 1 is returned, Len is the total length of the read -Out.write (buf,0, Len); -}
1InputStream in=S.getinputstream ();2File dir=NewFile ("C:\\pic");3 if(!dir.exists ()) {4 dir.mkdirs ();5 }6FileOutputStream fos=NewFileOutputStream ("Server.jpg");7 byte[] buf=New byte[1024];8 intLen=0;9 while((Len=in.read ())!=-1){TenFos.write (buf,0, Len); One } A
2. Using buffers as Buffers
1Using flow to output data
BufferedReader bufr=NewBufferedReader (NewFileReader ("Client.txt"));2 3 //by using PrintWriter to process the byte stream and the character stream, take over the stream4PrintWriter out =NewPrintWriter (S.getoutputstream (),true);5 6 //start reading, upload to service side7String line=NULL;8 while((Line=bufr.readline ())! =NULL){9 out.println (line);Ten}
1 //to put the received data into the stream2BufferedReader bufin=3 NewBufferedReader (NewInputStreamReader (S.getinputstream ()));4 5 //specifies the file to be written to6BufferedWriter bufw=NewBufferedWriter (NewFileWriter ("Server.txt"));7 8 //start reading9 //The default size of the buffer is 8k, one to 8k will automatically refresh, if there is no end flag, the resulting file size must be a multiple of 8TenString line=NULL; One while((Line=bufin.readline ())! =NULL){ A if("Over". Equals (line)) - Break; - Bufw.write (line); the bufw.newline (); - //Write your own refresh - Bufw.flush (); - } +
Write action in Java Network programming to get the source