import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class socket_Server {
ServerSocket server;
//MulticastSocket server;
public socket_Server(int port) throws IOException {
server = new ServerSocket(port);// 绑定端口号
//server=new MulticastSocket(port);
}
public void listen() throws IOException {
while (true) {
final Socket socket = server.accept();// 获取服务端接收到的socket
//MulticastSocket socket=server.
new Thread(new Runnable() {
public void run() {
try {
receiveFile(socket);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
public void receiveFile(Socket socket) throws IOException {
String filePath = "D:/temp/" + getDate() + "SJ"
+ new Random().nextInt(10000) + ".zip";
File f = new File("D:/temp");
if (!f.exists()) {
f.mkdir();// 没找到路径直接创建
}
FileOutputStream fos = new FileOutputStream(new File(filePath));
byte[] b = new byte[1024];
int length = 0;
DataInputStream dis = new DataInputStream(socket.getInputStream());
while ((length = dis.read(b, 0, length)) > 0) {
fos.write(b, 0, length);
fos.flush();
}// 完成接收
fos.close();
dis.close();
socket.close();
}
private String getDate() {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return df.format(new Date());
}
}
客户端:
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class socket_Client {
static Socket client;
public socket_Client(String ip, int port) throws UnknownHostException,
IOException {
client = new Socket(ip, port);
// 创建客户端socket,第一个参数ip,第二个端口与服务端端口与之对应
}
public String send(String msg) throws IOException {
File f=new File("D:/adbgjb.zip");
long l=f.length();//获取文件长度
DataOutputStream out=new DataOutputStream(client.getOutputStream());
FileInputStream fStream=new FileInputStream(f);
byte[] sendbytes=new byte[1024];
double sum=0;
int length=0;
while((length=fStream.read(sendbytes, 0, sendbytes.length))>0){
sum+=length;
System.out.println("当前发送进度:"+sum/l+"%");
out.write(sendbytes, 0, length);
out.flush();
}
fStream.close();
out.close();
client.close();
return null;
}
public void closeclient() throws IOException
{
client.close();
}
}