示例代码:
/**
* TCP服务端利用多线程解决并发上传
* @author 小苏
*
*/
public class TCP_Upload_Concurrent {
public static void main(String[] args) {
ServerSocket ss = null;
try {
//创建服务端绑定端口10005
ss = new ServerSocket(10005);
while(true){
Socket s = ss.accept();
//每连接一个客户端就创建一个线程
new Thread(new ServerThread(s)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerThread implements Runnable{
private Socket s;
public ServerThread(Socket s) {
this.s = s;
}
@Override
public void run() {
int num = 0;
FileOutputStream fos = null;
try {
String ip = s.getInetAddress().getHostAddress();
InputStream is = s.getInputStream();
byte[] buff = new byte[1024];
int len;
//给文件重命名
File file = new File("F://"+ip+num+".txt");
while(file.exists()){
file = new File("F://"+ip+"("+(num++)+")"+".txt");
}
fos = new FileOutputStream(file);
while((len = is.read(buff)) != -1){
fos.write(buff, 0, len);
}
OutputStream os = s.getOutputStream();
byte[] b = "接收完成".getBytes();
os.write(b );
} catch (Exception e) {
e.printStackTrace();
}finally{
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}