利用java socket实现文件传输

比如把一个文本从客户端传到服务器。可加分。我有一千多分呢。

1.服务器端

package sterning;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {
int port = 8821;

void start() {
Socket s = null;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
// 选择进行传输的文件
String filePath = "D:\\lib.rar";
File fi = new File(filePath);

System.out.println("文件长度:" + (int) fi.length());

// public Socket accept() throws
// IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。

s = ss.accept();
System.out.println("建立socket链接");
DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
dis.readByte();

DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
DataOutputStream ps = new DataOutputStream(s.getOutputStream());
//将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见Think In Java 4th里有现成的代码。
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long) fi.length());
ps.flush();

int bufferSize = 8192;
byte[] buf = new byte[bufferSize];

while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}

if (read == -1) {
break;
}
ps.write(buf, 0, read);
}
ps.flush();
// 注意关闭socket链接哦,不然客户端会等待server的数据过来,
// 直到socket超时,导致数据不完整。
fis.close();
s.close();
System.out.println("文件传输完成");
}

} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String arg[]) {
new ServerTest().start();
}
}

2.socket的Util辅助类

package sterning;

import java.net.*;
import java.io.*;

public class ClientSocket {
private String ip;

private int port;

private Socket socket = null;

DataOutputStream out = null;

DataInputStream getMessageStream = null;

public ClientSocket(String ip, int port) {
this.ip = ip;
this.port = port;
}

/** *//**
* 创建socket连接
*
* @throws Exception
* exception
*/
public void CreateConnection() throws Exception {
try {
socket = new Socket(ip, port);
} catch (Exception e) {
e.printStackTrace();
if (socket != null)
socket.close();
throw e;
} finally {
}
}

public void sendMessage(String sendMessage) throws Exception {
try {
out = new DataOutputStream(socket.getOutputStream());
if (sendMessage.equals("Windows")) {
out.writeByte(0x1);
out.flush();
return;
}
if (sendMessage.equals("Unix")) {
out.writeByte(0x2);
out.flush();
return;
}
if (sendMessage.equals("Linux")) {
out.writeByte(0x3);
out.flush();
} else {
out.writeUTF(sendMessage);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
if (out != null)
out.close();
throw e;
} finally {
}
}

public DataInputStream getMessageStream() throws Exception {
try {
getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
return getMessageStream;
} catch (Exception e) {
e.printStackTrace();
if (getMessageStream != null)
getMessageStream.close();
throw e;
} finally {
}
}

public void shutDownConnection() {
try {
if (out != null)
out.close();
if (getMessageStream != null)
getMessageStream.close();
if (socket != null)
socket.close();
} catch (Exception e) {

}
}
}

3.客户端

package sterning;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;

public class ClientTest {
private ClientSocket cs = null;

private String ip = "localhost";// 设置成服务器IP

private int port = 8821;

private String sendMessage = "Windwos";

public ClientTest() {
try {
if (createConnection()) {
sendMessage();
getMessage();
}

} catch (Exception ex) {
ex.printStackTrace();
}
}

private boolean createConnection() {
cs = new ClientSocket(ip, port);
try {
cs.CreateConnection();
System.out.print("连接服务器成功!" + "\n");
return true;
} catch (Exception e) {
System.out.print("连接服务器失败!" + "\n");
return false;
}

}

private void sendMessage() {
if (cs == null)
return;
try {
cs.sendMessage(sendMessage);
} catch (Exception e) {
System.out.print("发送消息失败!" + "\n");
}
}

private void getMessage() {
if (cs == null)
return;
DataInputStream inputStream = null;
try {
inputStream = cs.getMessageStream();
} catch (Exception e) {
System.out.print("接收消息缓存错误\n");
return;
}

try {
//本地保存路径,文件名会自动从服务器端继承而来。
String savePath = "E:\\";
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
int passedlen = 0;
long len=0;

savePath += inputStream.readUTF();
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath))));
len = inputStream.readLong();

System.out.println("文件的长度为:" + len + "\n");
System.out.println("开始接收文件!" + "\n");

while (true) {
int read = 0;
if (inputStream != null) {
read = inputStream.read(buf);
}
passedlen += read;
if (read == -1) {
break;
}
//下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比
System.out.println("文件接收了" + (passedlen * 100/ len) + "%\n");
fileOut.write(buf, 0, read);
}
System.out.println("接收完成,文件存为" + savePath + "\n");

fileOut.close();
} catch (Exception e) {
System.out.println("接收消息错误" + "\n");
return;
}
}

public static void main(String arg[]) {
new ClientTest();
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-10-07
java中的网络信息传输方式基于TCP协议和UD协议P的,socket是基于TCP协议的实现代码如下:
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
public class ClientTcpSend {
public static void main(String[] args) {
int length = 0;
byte[] sendBytes = null;
Socket socket = null;
DataOutputStream dos = null;
FileInputStream fis = null;
try {
try {
socket = new Socket();
socket.connect(new InetSocketAddress("127.0.0.1", 33456),
dos = new DataOutputStream(socket.getOutputStream());
File file = new File("/root/6674541037_c3a9c8b64c_b.jpg");
Ffis = new FileInputStream(file);
sendBytes = new byte[1024];
while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {
dos.write(sendBytes, 0, length);
dos.flush();
}
} finally {
if (dos != null)
dos.close();
if (fis != null)
fis.close();
if (socket != null)
socket.close();
}
} catch (Exception e) {
e.printStackTrace();

}

}

}
第2个回答  2011-10-14
代码如下:

/*
import java.io.*;
import java.net.*;
import java.util.*;
*/
private HttpURLConnection connection;//存储连接
private int downsize = -1;//下载文件大小,初始值为-1
private int downed = 0;//文加已下载大小,初始值为0
private RandomAccessFile savefile;//记录下载信息存储文件
private URL fileurl;//记录要下载文件的地址
private DataInputStream fileStream;//记录下载的数据流
try{
/*开始创建下载的存储文件,并初始化值*/
File tempfileobject = new File("h:\\webwork-2.1.7.zip");
if(!tempfileobject.exists()){
/*文件不存在则建立*/
tempfileobject.createNewFile();
}
savefile = new RandomAccessFile(tempfileobject,"rw");

/*建立连接*/
fileurl = new URL("https://webwork.dev.java.net/files/documents/693/9723/webwork-2.1.7.zip");
connection = (HttpURLConnection)fileurl.openConnection();
connection.setRequestProperty("Range","byte="+this.downed+"-");

this.downsize = connection.getContentLength();
//System.out.println(connection.getContentLength());

new Thread(this).start();
}
catch(Exception e){
System.out.println(e.toString());
System.out.println("构建器错误");
System.exit(0);
}
public void run(){
/*开始下载文件,以下测试非断点续传,下载的文件存在问题*/
try{
System.out.println("begin!");
Date begintime = new Date();
begintime.setTime(new Date().getTime());
byte[] filebyte;
int onecelen;
//System.out.println(this.connection.getInputStream().getClass().getName());
this.fileStream = new DataInputStream(
new BufferedInputStream(
this.connection.getInputStream()));
System.out.println("size = " + this.downsize);
while(this.downsize != this.downed){
if(this.downsize - this.downed > 262144){//设置为最大256KB的缓存
filebyte = new byte[262144];
onecelen = 262144;
}
else{
filebyte = new byte[this.downsize - this.downed];
onecelen = this.downsize - this.downed;
}
onecelen = this.fileStream.read(filebyte,0,onecelen);
this.savefile.write(filebyte,0,onecelen);
this.downed += onecelen;
System.out.println(this.downed);
}
this.savefile.close();
System.out.println("end!");
System.out.println(begintime.getTime());
System.out.println(new Date().getTime());
System.out.println(begintime.getTime() - new Date().getTime());
}
catch(Exception e){
System.out.println(e.toString());
System.out.println("run()方法有问题!");
}
}

/***
//FileClient.java
import java.io.*;
import java.net.*;
public class FileClient {
public static void main(String[] args) throws Exception {

//使用本地文件系统接受网络数据并存为新文件

File file = new File("d:\\fmd.doc");

file.createNewFile();

RandomAccessFile raf = new RandomAccessFile(file, "rw");

// 通过Socket连接文件服务器

Socket server = new Socket(InetAddress.getLocalHost(), 3318);
//创建网络接受流接受服务器文件数据
InputStream netIn = server.getInputStream();
InputStream in = new DataInputStream(new BufferedInputStream(netIn));
//创建缓冲区缓冲网络数据

byte[] buf = new byte[2048];

int num = in.read(buf);

while (num != (-1)) {//是否读完所有数据

raf.write(buf, 0, num);//将数据写往文件

raf.skipBytes(num);//顺序写文件字节

num = in.read(buf);//继续从网络中读取文件

}
in.close();
raf.close();
}
}

//FileServer.java
import java.io.*;
import java.util.*;
import java.net.*;
public class FileServer {
public static void main(String[] args) throws Exception {

//创建文件流用来读取文件中的数据

File file = new File("d:\\系统特点.doc");

FileInputStream fos = new FileInputStream(file);

//创建网络服务器接受客户请求

ServerSocket ss = new ServerSocket(8801);

Socket client = ss.accept();

//创建网络输出流并提供数据包装器

OutputStream netOut = client.getOutputStream();

OutputStream doc = new DataOutputStream(
new BufferedOutputStream(netOut));

//创建文件读取缓冲区

byte[] buf = new byte[2048];

int num = fos.read(buf);
while (num != (-1)) {//是否读完文件
doc.write(buf, 0, num);//把文件数据写出网络缓冲区
doc.flush();//刷新缓冲区把数据写往客户端
num = fos.read(buf);//继续从文件中读取数据
}
fos.close();
doc.close();
}
}
*/