62,615
社区成员
发帖
与我相关
我的任务
分享
//客户端
import java.io.*;
import java.net.*;
/*
* 需求:客户端并发上传图片
*/
public class Tcp练习4
{
public static void main(String [] args)throws Exception
{
if(args.length!=1)
{
System.out.println("输入信息长度必须唯一");
return;
}
String filename=args[0];
File file=new File(filename);
if(!(file.exists()&&file.isFile()))
{
System.out.println("文件不存在或不是文件");
return;
}
Socket soc=new Socket(InetAddress.getLocalHost(),9000);
FileInputStream fr=new FileInputStream(file);
OutputStream out=soc.getOutputStream();
InputStream in=soc.getInputStream();
System.out.println(filename);
//将文件名发给客户端
PrintStream pp=new PrintStream(out,true);
pp.println(filename);
int len;
byte [] buf=new byte[1024];
while((len=fr.read(buf))!=-1)
{
out.write(buf,0,len);
}
soc.shutdownOutput();
len=in.read(buf);
System.out.println(new String(buf,0,len));
soc.close();
in.close();
out.close();
fr.close();
}
}
//服务端
//package a;
import java.io.*;
import java.net.*;
/*
* 客户端的并发上传文件的原理。(凡是服务器都这样)
* 获得一个连接启动一个线程(run方法)
*/
class FileThread implements Runnable
{
private Socket soc;
FileThread(Socket soc)
{
this.soc=soc;
}
public void run()
{
try
{
String ip=soc.getInetAddress().getHostAddress();
System.out.println(ip+" connected");
InputStream in=soc.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String path=br.readLine();
//System.out.println(name);
//String [] ss=name.split("/.");
String name=path.substring(0, path.lastIndexOf('.'));
String format=path.substring(path.lastIndexOf('.'));
int count=1;
byte [] buf=new byte[1024];
int len;
//stem.out.println(ss.length);
File file=new File(name+"("+count+")"+format);
while(file.exists())
{
count++;
file=new File(name+"("+count+")"+format);
}
FileOutputStream fos=new FileOutputStream(file);//////////////////////////////////
OutputStream out=soc.getOutputStream();
while((len=in.read(buf))!=-1)
{
fos.write(buf, 0, len);
}
out.write("上传成功".getBytes());
in.close();
out.close();
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
throw new RuntimeException("服务端出错");
}
}
}
public class 练习Server4
{
public static void main(String [] ars)throws Exception
{
ServerSocket sersoc=new ServerSocket(9000);
while(true)
{
Socket soc=sersoc.accept();
new Thread(new FileThread(soc)).start();
}
}
}