客户端:
package ThreadTcp;
import java.io.*;
import java.net.Socket;
public class clicentThread {
public static void main(String[] args) throws IOException {
Socket s=new Socket("192.168.1.9",23456);
BufferedReader br=new BufferedReader(new FileReader("copy.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 brc=new BufferedReader(new InputStreamReader(s.getInputStream()));
String data=brc.readLine();
System.out.println(data);
br.close();
s.close();
}
}
服务端:
package ThreadTcp;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerThread {
public static void main(String[] args) throws IOException {
ServerSocket ss =new ServerSocket(23456);
while (true){
Socket s = ss.accept();
new Thread(new serThread(s)).start();
}
}
}
线程类:
package ThreadTcp;
import java.io.*;
import java.net.Socket;
public class serThread implements Runnable {
private Socket s;
public serThread(Socket s) {
this.s=s;
}
@Override
public void run() {
try {
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter bw=new BufferedWriter(new FileWriter("copy"+Thread.currentThread().getName()+".java"));
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();
}
}
}