TCP通信程序练习(多线程实现文件上传)

package NetworkProgramming.TCP.SocketDemo06;

import java.io.*;
import java.net.Socket;

/**
* FileName: ClientDmeo
* Author: lps
* Date: 2022/4/2 16:11
* Sign:刘品水 Q:1944900433
*/
public class ClientDemo {
public static void main(String[] args) throws IOException {
Socket s = new Socket("192.168.10.102",10086);
BufferedReader br = new BufferedReader(new FileReader("F:\\IdeaProjects\\bos.java"));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String line;
while ((line= br.readLine())!=null){
bw.write(line);
bw.newLine();
bw.flush();
}
//自定义结束标记
// bw.write("886");
// bw.newLine();
// bw.flush();
////void shutdownInput()
// //将此套接字的输入流放在“流结束”中。
// //void shutdownOutput()
// //禁用此套接字的输出流。
s.shutdownOutput();

BufferedReader brClient = new BufferedReader(new InputStreamReader(s.getInputStream()));
String data= brClient.readLine();
System.out.println("服务器端的反馈为:"+data);


br.close();
s.close();

}
}

package NetworkProgramming.TCP.SocketDemo06;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
* FileName: ServerDemo
* Author: lps
* Date: 2022/4/2 16:11
* Sign:刘品水 Q:1944900433
*/
public class ServerDemo {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10086);
while (true){
Socket s = ss.accept();
new Thread(new ServerThread(s)).start();

}

}
}

package NetworkProgramming.TCP.SocketDemo06;

import java.io.*;
import java.net.Socket;

/**
* FileName: ServerThread
* Author: lps
* Date: 2022/4/2 18:30
* Sign:刘品水 Q:1944900433
*/
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()));
//BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\IdeaProjects\\Copy.java"));
//解决名称冲突问题
int count = 0;
File file = new File("F:\\IdeaProjects\\Copy[+" + count + "].java");
while (file.exists()) {
count++;
file=new File("F:\\IdeaProjects\\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 Serverbw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
Serverbw.write("已收到文件,成功");
Serverbw.newLine();
Serverbw.flush();

s.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}

 

posted @ 2022-04-02 19:32  刘品水  阅读(49)  评论(0编辑  收藏  举报