JAVA TCP结合线程使用
2022/4/17 17:12:43
本文主要是介绍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(); } }
这篇关于JAVA TCP结合线程使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-27消息中间件底层原理资料详解
- 2024-11-27RocketMQ底层原理资料详解:新手入门教程
- 2024-11-27MQ底层原理资料详解:新手入门教程
- 2024-11-27MQ项目开发资料入门教程
- 2024-11-27RocketMQ源码资料详解:新手入门教程
- 2024-11-27本地多文件上传简易教程
- 2024-11-26消息中间件源码剖析教程
- 2024-11-26JAVA语音识别项目资料的收集与应用
- 2024-11-26Java语音识别项目资料:入门级教程与实战指南
- 2024-11-26SpringAI:Java 开发的智能新利器