您的位置:首页 > 编程语言 > Java开发

java socket 使用 多线程下载请求

2016-03-15 16:40 375 查看
<pre name="code" class="java">import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
//服务端源码 异步处理客户请求
public class Server {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ServerSocket serverSocket=new ServerSocket(8988);
while(true){
Socket socket=serverSocket.accept();
Thread thread=new Thread(new Server.SendFile(socket));
thread.start();
}
}
static class SendFile implements Runnable{
private Socket socket;
public SendFile(Socket socket){
this.socket=socket;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
FileInputStream fileInputStream=new FileInputStream(new File("G:\\迅雷下载\\[05美国动作片][Constantine.地狱神探][HR-HDTV][x264][双语字幕][YYeTs人人影视]\\Constantine.地狱神探.双语字幕.HR-HDTV.AC3.1024X576.x264-人人影视制作.mkv"));
byte[] readUnit=new byte[1024];
OutputStream outputStream=socket.getOutputStream();
while(fileInputStream.read(readUnit)!=-1){
outputStream.write(readUnit);
}
fileInputStream.close();
outputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
//客户端源码 模拟多个客户下载请求操作
public class Client implements Runnable {

private Socket socket;
private int no;
public Client(Socket socket,int no){
this.socket=socket;
this.no=no;
}
@Override
public void run() {
// TODO Auto-generated method stub
InputStream inputStream;
try {
System.out.println("No"+no);
inputStream = socket.getInputStream();
byte[] unitData=new byte[1024];
FileOutputStream fileOutputStream=new FileOutputStream(new File("G:\\迅雷下载\\fan\\"+no+".mkv"));
while(inputStream.read(unitData)!=-1){
fileOutputStream.write(unitData);
}
<span style="white-space:pre">			</span>//需要关闭流
<span style="white-space:pre">			</span>inputStream.close();
<span style="white-space:pre">			</span>fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
for(int i=0;i<2;i++){
System.out.println("No."+i+" Thread");
Socket socket = new Socket("localhost",8988);
Thread thread=new Thread(new Client(socket,i));
thread.start();
}
}

}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: