一个正常的服务器应该是可以允许多个用户同时上传文件的,但是怎么上传呢?
原理:用多线程封装取到的Socket对象,并进行处理,分别作不同处理
/*
*客户端
*/
package Demo13ThreadTCP;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("127.0.0.1",10000);
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
// bos.write("C:\\Users\\user\\Desktop\\aaa.txt".getBytes());
// bos.flush();
File file = new File("C:\\Users\\user\\Desktop\\1.txt");
BufferedInputStream textIn = new BufferedInputStream(new FileInputStream(file));
byte[] buf = new byte[1024];
int len = 0;
BufferedInputStream bs = new BufferedInputStream(s.getInputStream());
while((len=textIn.read(buf))!=-1){
System.out.println(new String(buf,0,len));
bos.write(buf,0,len);
}
bos.flush();
s.shutdownOutput();
// bos.flush();
len = bs.read(buf);
System.out.println(new String(buf,0,len));
s.close();
}
}
/*
*服务端
*/
package Demo13ThreadTCP;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Service {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10000);
while(true){
Socket s = ss.accept();
ServiceThread st = new ServiceThread(s);
Thread t = new Thread(st);
String ip = s.getInetAddress().getHostName();
System.out.println("ip:"+ip+"连接");
t.start();
}
}
}
class ServiceThread implements Runnable{
private Socket s;
public ServiceThread(Socket s){
this.s = s;
}
@Override
public void run() {
try {
BufferedInputStream bs = new BufferedInputStream(s.getInputStream());
byte[] buf = new byte[1024];
int len = 0;
// int textNameLength = bs.read(buf);
// String textName = new String(buf,0,textNameLength,"utf-8");
// System.out.println(textName);
File textFile = new File("C:\\Users\\user\\Desktop\\aaa.txt");
BufferedOutputStream textOut= new BufferedOutputStream(new FileOutputStream(textFile));
while((len=bs.read(buf))!=-1){
System.out.println(new String(buf,0,len));
textOut.write(buf,0,len);
}
textOut.flush();
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
bos.write("上传成功!".getBytes());
bos.flush();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
|