一、练习需求
客户端:数据来自文本文件,接收服务器反馈
服务器:接收到的数据写入文本文件,给出反馈,代码用线程进行封装,为每一个客户端开启一个线程
二、代码
客户端:
import java.io.*; import java.net.Socket; /* 客户端,数据来自于文本文件,接收服务器反馈 */ public class ClientDemo005 { public static void main(String[] args) throws IOException { //创建客户端Socket对象 Socket s = new Socket("192.168.190.166", 10000); //封装文本文件的数据 BufferedReader br = new BufferedReader(new FileReader("hello.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); //释放资源 br.close(); s.close(); } }
ServerThread方法:
import java.io.*; import java.net.Socket; 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("Copy["+count+"].java"); while(file.exists()){ count++; file = new File("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(); //释放资源 s.close(); } catch (IOException e) { e.printStackTrace(); } } }
服务器:
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /* 服务器:接收到的数据写入文本文档,给出反馈,代码用线程进行封装,为每个客户端开启一个线程 */ public class ServerDemo005 { public static void main(String[] args) throws IOException { //创建服务器Socket对象 ServerSocket ss = new ServerSocket(10000); while(true) { //监听客户端连接,返回一个对应的Socket对象 Socket s = ss.accept(); //为每一个客户端开启一个线程 new Thread(new ServerThread(s)).start(); } } }
三、运行结果
控制台:
文件: