客户端
Cleint.java
public class Client {
public static void main(String[] args) {
try (Socket socket = new Socket("10.0.179.204", 11000)) {
FileInputStream fis = new FileInputStream("src/plant.txt");
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
int length;
byte[] bytes = new byte[1024];
while((length = fis.read(bytes)) != -1){
os.write(bytes,0,length);
}
/*
* 禁用此套接字的输出流。对于 TCP 套接字,任何以前写入的数据都将被发送,并且后跟 TCP 的正常连接终止序列。 如果在套接字上调用 shutdownOutput() 后写入套接字输出流,则该流将抛出 IOException。否则会出现错误。
* */
socket.shutdownOutput();
byte[] bytes1 = new byte[1024];
int num = is.read(bytes1);
System.out.println(new String(bytes1,0,num));
fis.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户子线程
UserThread.javapublic class UserThread implements Runnable {
private Socket s;
public UserThread(Socket s) {
this.s = s;
}
@Override
public void run() {
try {
OutputStream os = s.getOutputStream();
InputStream is = s.getInputStream();
int count=1;
File f = new File("d:\\test"+"("+count+")"+".txt");//由于是多个不同的客户端向服务端传送文件,所以要考虑文件重名,导致被覆盖。
while (f.exists()) {
f = new File("d:\\test"+"("+ count++ +")"+".txt");
}
FileOutputStream fos = new FileOutputStream(f);
byte[] bytes = new byte[1024];
int length;
while (((length = is.read(bytes)) != -1)) {
fos.write(bytes, 0, length);
}
os.write("成功".getBytes());
fos.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端Server.java
public class Sever {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(11000);
while (true) {
Socket s = ss.accept();
new Thread(new UserThread(s)).start();
}
} catch(IOException e){
e.printStackTrace();
}
}
}