服务端
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class TcpClients {
public static void main(String[] args) throws Exception, Exception {
Socket socket=new Socket("127.0.0.1",6000);
OutputStream out= socket.getOutputStream();
FileInputStream fis=new FileInputStream(new File("d:/客户端目录/天使彦.bmp"));
byte [] bytes=new byte[1024];
int len;
while((len=fis.read(bytes))!=-1) {
out.write(bytes,0,len);
}
socket.shutdownOutput();
InputStream in=socket.getInputStream();
len=in.read(bytes);
System.out.println(new String(bytes,0,len));
fis.close();
socket.close();
}
}
服务器线程
import java.io.File;
import java.io.FileOutputStream;
import java.net.Socket;
import java.util.Random;
public class Tcp implements Runnable{
private Socket socket;
public Tcp(Socket socket) {
this.socket=socket;
}
@Override
public void run() {
try {
System.out.println("服务器开启成功!");
File file=new File("d:/服务器目录");
if(!file.exists()) {
file.mkdirs();
}
String filename="cn.edu360-"+System.currentTimeMillis()+new Random().nextInt(999999)+".bmp";
FileOutputStream fos=new FileOutputStream(file+"/"+filename);
byte[] bytes =new byte[1024];
int len;
while((len=socket.getInputStream().read(bytes))!=-1) {
fos.write(bytes, 0, len);
}
socket.getOutputStream().write("上传完成".getBytes());
fos.close();
}catch(Exception e) {
}
}
}
开启服务器
import java.net.ServerSocket;
import java.net.Socket;
public class TCPSeversThread {
public static void main(String[] args) throws Exception {
ServerSocket ser=new ServerSocket(6000);
while(true) {
Socket socket=ser.accept();
new Thread(new Tcp( socket)).start();
}
}
}
实现服务器永不停息,有新客户端连入即可上传。