服务器文件上传
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
while (true){
Socket socket = serverSocket.accept();
//使用多线程,提高线程的效率
//有一个客户端上传文件,我就开启一个线程,完成上传文件
new Thread(new Runnable() {
//完成上传文件
@Override
public void run() {
try {
InputStream inputStream = socket.getInputStream();
File file = new File("f:\\upload");
if (!file.exists()){
file.mkdir();
}
String fileName = "lixy"+System.currentTimeMillis()+new Random().nextInt(10)+".txt";
FileOutputStream fos = new FileOutputStream(file + "\\" + fileName);
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) != -1){
fos.write(bytes,0,len);
}
OutputStream outputStream = socket.getOutputStream();
outputStream.write("上传成功".getBytes());
fos.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
//serverSocket.close();
}
}
public class TCPClient {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("F:\\intellij idea\\net\\a.txt");
Socket socket = new Socket("127.0.0.1", 8888);
OutputStream outputStream = socket.getOutputStream();
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fis.read(bytes)) != -1){
outputStream.write(bytes,0,len);
}
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
while ((len = inputStream.read(bytes)) != -1){
System.out.println(new String(bytes,0,len));
}
fis.close();
socket.close();
}
}