Design requirement: Upload TXT file from client to server, send message to client after receiving file.
1. Server side:
public class Uploadfileserver {
public static void Main (string[] args) throws Exception {
ServerSocket ss = new ServerSocket (10010);
Socket s =ss.accept ();
BufferedReader Bufin = new BufferedReader (New InputStreamReader (S.getinputstream ()));
BufferedWriter BUFW =new BufferedWriter (New FileWriter ("D:\\server.txt"));
String line1 =null;
while ((Line1=bufin.readline ())!=null)
{
Bufw.write (Line1,0,line1.length ());
}
SYSTEM.OUT.PRINTLN ("The server is finished receiving ....") ");
PrintWriter out = new PrintWriter (S.getoutputstream (), true);
Out.println ("Upload success");
SYSTEM.OUT.PRINTLN ("Service End feedback client finished ....") ");
Bufw.close ();
S.close ();
Ss.close ();
}
}
2. Client:
public class Uploadfileclient {
public static void Main (string[] args) throws Exception {
Socket s = new socket ("192.168.5.163", 10010);
File file =new file ("D:\\1.txt");
BufferedReader Buffer =new BufferedReader (new FileReader (file));
PrintWriter out = new PrintWriter (S.getoutputstream (), true);
String line =null;
while ((Line=buffer.readline ())!=null)
{
Out.println (line);
SYSTEM.OUT.PRINTLN ("client reads the contents of the file" +line);
}
SYSTEM.OUT.PRINTLN ("The client has finished ..... ");
BufferedReader Bufin = new BufferedReader (New InputStreamReader (S.getinputstream ()));
S.shutdownoutput ();
String Result=bufin.readline ();
SYSTEM.OUT.PRINTLN ("The client has received data from the server ..... ");
SYSTEM.OUT.PRINTLN (result);
Buffer.close ();
S.close ();
}
}
Small summary: Before the run has been unsuccessful, debugging found that the client side of the data has been transmitted, but the server side has been waiting for the client to continue to pass the data, and has not been to write the received data into the file. After adding: S.shutdownoutput () on the client, the file can be uploaded successfully.
Java Network Programming (v)----TDP step-by-step article upload text file