//客户端
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class FileClient {
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
Socket socket=new Socket("localhost",8888);
OutputStream out=socket.getOutputStream();
FileInputStream fis=new FileInputStream("D:\\1.png");
byte[] buf=new byte[1024];
int len;
while((len=fis.read(buf))!=-1) {
out.write(buf,0,len);
}
socket.shutdownOutput();
InputStream in=socket.getInputStream();
byte[] bufMsg=new byte[1024];
int num=in.read(bufMsg);
String Msg=new String(bufMsg,0,num);
System.out.println(Msg);
fis.close();
socket.close();
}
}
//服务端
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
public static void main(String[] args) throws IOException {
ServerSocket serverscoket=new ServerSocket(8888);
while(true) {
Socket s=serverscoket.accept();
new Thread(new ServerThread(s)).start();
}
}
}
class ServerThread implements Runnable{
private Socket socket;
public ServerThread(Socket socket) {
this.socket=socket;
}
@Override
public void run() {
// TODO Auto-generated method stub
String ip=socket.getInetAddress().getHostAddress();
int count=1;
try {
InputStream in=socket.getInputStream();
File parentFile=new File("D:\\upload\\");
if(!parentFile.exists()) {
parentFile.mkdir();
}
File file=new File(parentFile,ip+"("+count+").png");
while(file.exists()) {
file=new File(parentFile,ip+"("+(count++)+").png");
}
FileOutputStream fos=new FileOutputStream(file);
byte[] buf=new byte[1024];
int len=0;
while((len=in.read(buf))!=-1) {
fos.write(buf,0,len);
}
OutputStream out=socket.getOutputStream();
out.write("上传成功".getBytes());
fos.close();
socket.close();
}catch(Exception e) {
throw new RuntimeException(e);
}
}
}
//写到2个java文件中,在eclipse中先运行服务端后运行客户端
java网络编程 -学习篇(3)TCP文件上传
最新推荐文章于 2021-08-27 00:25:33 发布