TCP data Transfer (V): Upload a text file and give feedback
import Java.io.BufferedReader;
import Java.io.BufferedWriter;
import Java.io.FileWriter;
import java.io.IOException;
import Java.io.InputStreamReader;
import Java.io.OutputStreamWriter;
import Java.net.ServerSocket;
import Java.net.Socket;
Public class Uploadserver {
Public static void main (string[] args)throws IOException {
// Create a server-side Socket Object
ServerSocketss = Newserversocket (11111);
// Listening for client connections
Sockets = Ss.accept (); // Blocking
// flow within the encapsulated channel
BUFFEREDREADERBR = newbufferedreader (newInputStreamReader (
S.getinputstream ()));
// Encapsulating text Files
BUFFEREDWRITERBW = newbufferedwriter (newFileWriter ("Copy.java"));
Stringline = null;
while (line = Br.readline ()) =null) { // block
//if ("over". Equals (line)) {
//break;
// }
Bw.write (line);
Bw.newline ();
Bw.flush ();
}
// Give the feedback
Bufferedwriterbwserver = newbufferedwriter (newOutputStreamWriter (
S.getoutputstream ()));
Bwserver.write (" file Upload succeeded ");
Bwserver.newline ();
Bwserver.flush ();
// Freeing Resources
Bw.close ();
S.close ();
}
}
import Java.io.BufferedReader;
import Java.io.BufferedWriter;
import Java.io.FileReader;
import java.io.IOException;
import Java.io.InputStreamReader;
import Java.io.OutputStreamWriter;
import Java.net.Socket;
/*
* The feedback was added according to our normal thinking, but the results didn't respond. Why is it ?
* reading a text file is possible to NULL as an end message, however, there is no way to end the message in the channel.
* so the server doesn't even know you're done. And you want the server to give you feedback. So, we waited for each other.
*
* How to fix it? ?
* A: write one more piece of data, tell the server, read this data and I'm done, and you're done.
* This will solve the problem, but it's not good.
* B:socket object provides a solution
* Publicvoid Shutdownoutput ()
*/
Public class uploadclient {
Public static void main (string[] args)throws IOException {
// Create client Socket Object
Sockets = newSocket ("192.168.12.92", 11111);
// Encapsulating text Files
BUFFEREDREADERBR = newbufferedreader (newFileReader (
"Inetaddressdemo.java"));
// Package Channel Internal flow
BUFFEREDWRITERBW = newbufferedwriter (newOutputStreamWriter (
S.getoutputstream ()));
Stringline = null;
while (line = Br.readline ()) =null) { // block
Bw.write (line);
Bw.newline ();
Bw.flush ();
}
// customizing an end tag
Bw.write ("over");
Bw.newline ();
Bw.flush ();
//socket provides a termination, it notifies the server you don't have to wait, I don't have the data .
S.shutdownoutput ();
// Receive Feedback
Bufferedreaderbrclient = newbufferedreader (newInputStreamReader (
S.getinputstream ()));
Stringclient = Brclient.readline (); // Blocking
System. out. println (client);
// Freeing Resources
Br.close ();
S.close ();
}
}
TCP data Transfer (V): Upload a text file and give feedback