JAVA TCP结合线程使用
package Inter; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class ServeDemo { public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(10000); while (true){ Socket s = ss.accept(); new Thread(new ServerThread(s)).start(); } } }
package Inter; 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("./cc_" + count + ".txt"); while (file.exists()){ count++; file = new File("./cc_" + count + ".txt"); } BufferedWriter bw = new BufferedWriter(new FileWriter(file)); String line; while ((line=br.readLine()) != null){ bw.write(line); bw.newLine(); bw.flush(); } BufferedWriter brw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); brw.write("文件上传成功!"); brw.newLine(); brw.flush(); }catch (IOException e){ e.printStackTrace(); } } }
package Inter; import java.io.*; import java.net.Socket; public class ClientDemo { public static void main(String[] args) throws IOException { Socket s = new Socket("127.0.0.1",10000); // BufferedReader br = new BufferedReader(new FileReader("./1.txt")); 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 bu = new BufferedReader(new InputStreamReader(s.getInputStream())); String line1 = bu.readLine(); System.out.println("服务器反馈:"+line1); bu.close(); bw.close(); br.close(); } }