JavaTCP Upload Text File Code
- 2021-06-28 12:39:32
- OfStack
File transfer based on chat client (TXT file)
Client Code:
public class UploadClient {
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
//1 , create socket Client Object
Socket s = new Socket("localhost",10005);
//2 , read local files
BufferedReader bufr = new BufferedReader(new FileReader("C:\\ New Folder \\client.txt"));
//3 , Socket flow
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
String line = null;
while((line=bufr.readLine())!=null){
out.println(line);
}
// Tell the server that the client is done
s.shutdownOutput();
//4 Read the upload success object returned by the server
BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = bufIn.readLine();
System.out.println(str);
// close resource
bufr.close();
s.close();
}
}
Server side code:
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
//1,
ServerSocket ss = new ServerSocket(10005);
//2, Obtain Socket object
Socket s = ss.accept();
// Obtain IP
System.out.println(s.getInetAddress().getHostAddress()+"....conected");
//3, Obtain Socket Read streams and decorate
BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
//4, write file
BufferedWriter bufw = new BufferedWriter(new FileWriter("C:\\ New Folder \\server.txt"));
String line = null;
while((line=bufIn.readLine())!=null){
bufw.write(line);
bufw.newLine();// Line Break
bufw.flush();// Refresh Stream
}
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
out.println(" Upload Successful ");
bufw.close();
s.close();// Close Client
ss.close();// Close Server
}
It should be noted that in the TCP transport, 1 must run the server before the client.
summary