基于聊天客户端的基础上的文件(TXT文件)传输 客户端代码: public class UploadClient { public static void main(String[] args) throws UnknownHostException, IOException { // TODO Auto-generated method stub //1,创建
基于聊天客户端的基础上的文件(TXT文件)传输
客户端代码:
public class UploadClient { public static void main(String[] args) throws UnknownHostException, IOException { // TODO Auto-generated method stub //1,创建socket客户端对象 Socket s = new Socket("localhost",10005); //2,读取本地文件 BufferedReader bufr = new BufferedReader(new FileReader("C:\\新建文件夹\\client.txt")); //3,Socket流 PrintWriter out = new PrintWriter(s.getOutputStream(),true); String line = null; while((line=bufr.readLine())!=null){ out.println(line); } //告诉服务端,客户端写完了 s.shutdownOutput(); //4,读取服务端返回的上传成功对象 BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); String str = bufIn.readLine(); System.out.println(str); //关闭资源 bufr.close(); s.close(); } }
服务端代码:
public static void main(String[] args) throws UnknownHostException, IOException { // TODO Auto-generated method stub //1, ServerSocket ss = new ServerSocket(10005); //2,获取Socket对象 Socket s = ss.accept(); //获取IP System.out.println(s.getInetAddress().getHostAddress()+"....conected"); //3,获取Socket读取流,并装饰 BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); //4,写入文件 BufferedWriter bufw = new BufferedWriter(new FileWriter("C:\\新建文件夹\\server.txt")); String line = null; while((line=bufIn.readLine())!=null){ bufw.write(line); bufw.newLine();//换行 bufw.flush();//刷新流 } PrintWriter out = new PrintWriter(s.getOutputStream(),true); out.println("上传成功"); bufw.close(); s.close();//关闭客户端 ss.close();//关闭服务端 }
要注意的是TCP传输中,一定要先运行服务端再运行客户端。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对自由互联的支持。如果你想了解更多相关内容请查看下面相关链接