您的位置:首页 > 编程语言 > Java开发

JAVA Socket:文件传输

2016-04-05 17:47 561 查看
客户端:读取文件(FileInputStream),发送文件(OutputStream)

服务器端:接收文件(InputStream),写文件(FileOutputStream)

客户端代码:

package socketCopyFile;
import java.net.*;
import java.io.*;
public class SocketCopyFileC {

public static void main(String[] args) {
try {
Socket s = new Socket("127.0.0.1", 8888);
System.out.println("getPort:" + s.getPort() + " getLocalPort:" + s.getLocalPort());
OutputStream ops = s.getOutputStream();
FileInputStream fis = new FileInputStream("C:/ice.jpg");
byte[] b = new byte[1024];

@SuppressWarnings("unused")
int nLength = -1;
while ((nLength = fis.read(b)) > 0){
ops.write(b,0,nLength);
}

fis.close();
ops.close();
s.close();
} catch (UnknownHostException e) {

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

e.printStackTrace();
}finally{
System.out.println("客户端Over");
}

}

}


服务器端代码:

package socketCopyFile;

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

public class SocketCopyFileS {

public static void main(String[] args) {
try {
ServerSocket sSocket = new ServerSocket(8888);
Socket s = sSocket.accept();
System.out.println("getPort:" + s.getPort() + " getLocalPort:" + s.getLocalPort());
InputStream ips = s.getInputStream();
FileOutputStream fos = new FileOutputStream("D:\\ice.jpg");

byte[] b = new byte[1024];
int nLen = -1;
while(true){
nLen = ips.read(b);

if (nLen == -1){
break;
}
fos.write(b, 0 , nLen);
}

fos.close();
ips.close();

s.close();
sSocket.close();

} catch (Exception e) {

}finally{
System.out.println("服务器端,OVER");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: