标签:class address 文件上传 edr sys ace write lin ade
客户端代码:
public class ClientDemo { public static void main(String[] args) throws IOException { //创建客户端Scoket对象 Socket s= new Socket("192.168.50.76",44444); //封装文本文件数据 BufferedReader br = new BufferedReader(new FileReader("myNet\\InetAddressDemo.java")); //输出流 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); String line; while ((line = br.readLine())!=null){ bw.write(line); bw.newLine(); bw.flush(); } //使输出终止 s.shutdownOutput(); //客户端接收反馈 BufferedReader brClient = new BufferedReader(new InputStreamReader(s.getInputStream())); String data = brClient.readLine(); System.out.println("服务器的反馈:"+data); //释放资源 s.close(); br.close(); } }
服务器端代码:
public class ServerDemo { public static void main(String[] args) throws IOException { //创建客户端Socket对象 ServerSocket ss = new ServerSocket(44444); //为每一个客户端开启一个线程 while (true) { //监听客户端连接 Socket s = ss.accept(); new Thread(new ServerThread(s)).start(); } } }
实现Runnable接口的SeverThread类:
public class ServerThread implements Runnable{ private Socket s; public ServerThread(Socket s) { this.s=s; } @Override public void run() { //接受数据写入到文件 try { BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); //解决名称冲突问题 int count = 0; File file = new File("myNet\\Copy["+count+"].java"); while (file.exists()){ count++; file = new File("myNet\\Copy["+count+"].java"); } BufferedWriter bw = new BufferedWriter(new FileWriter(file)); String line; while ((line=br.readLine())!=null){ bw.write(line); bw.newLine(); bw.flush(); } //给出反馈 BufferedWriter bwServer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); bwServer.write("文件上传成功"); bwServer.newLine(); bwServer.flush(); }catch (IOException e){ e.printStackTrace(); } } }
运行结果:客户端程序每上传一次文件,服务器都会给出一次反馈
标签:class address 文件上传 edr sys ace write lin ade
原文地址:https://www.cnblogs.com/pxy-1999/p/12871991.html