发布网友 发布时间:2022-04-22 20:21
共2个回答
热心网友 时间:2022-05-02 09:18
客户端代码如下:
import java.io.DataOutputStream;服务端代码如下:
import java.io.DataInputStream;热心网友 时间:2022-05-02 10:36
哈哈,这个我会啊!!!
给你个! 给我分吧!!!
//客户端
package socket;
import java.net.*;
import java.io.*;
/**
* SocketServer从SocketClient接受文件名,将文件发送到SocketServer端保存!
*
*
*/
public class SocketClient {
private static File f = null;
private static FileInputStream fr = null;
private static DataOutputStream dout = null;
private static Socket s = null;
public static void main(String[] args) {
SocketClient sc = new SocketClient();
sc.connectSocketServer(1234);
sc.sendFile("li.txt");
}
/**
* 连接服务器端
*
* @param port
* 要连接的服务器SocketServer端口
*/
public void connectSocketServer(int port) {
try {
s = new Socket(InetAddress.getLocalHost(), port);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 发送文件
public void sendFile(String str) {
byte[] b = new byte[1024];
f = new File(str);
try {
//数据输出流
dout = new DataOutputStream(new BufferedOutputStream(s
.getOutputStream()));
//文件读入流
fr = new FileInputStream(f);
int n = fr.read(b);
while (n != -1) {
//向网络中写入数据
dout.write(b, 0, n);
dout.flush();
//再次读取n字节
n = fr.read(b);
}
//关闭流
fr.close();
dout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//服务器端
package socket;
import java.net.*;
import java.io.*;
/**
* Socketserver从客户端读取文件并保存为本地文件!
*
*
*/
public class Socketserver {
private static ServerSocket ss = null;
private static Socket s = null;
private static File f = null;
private static RandomAccessFile fw = null;
public static void main(String[] args) {
Socketserver sk = new Socketserver();
sk.initServer(1234);
sk.getFile();
}
/**
* 初始化服务器端
* @param port
* 服务器端要使用的端口
*/
public void initServer(int port){
try {
ss = new ServerSocket(port);
s = ss.accept();
} catch (IOException e) {
e.printStackTrace();
}
}
// 从SocketClient读取文件
public void getFile() {
byte[] b = new byte[1024];
try {
//定义输入流,s.getInputStream();
InputStream in = s.getInputStream();
DataInputStream din = new DataInputStream(new BufferedInputStream(
in));
//创建要保存的文件
f = new File("copy.txt");
fw = new RandomAccessFile(f, "rw");
int num = din.read(b);
while (num != -1) {
//向文件中写入0~num个字节
fw.write(b, 0, num);
//跳过num个字节再次写入文件
fw.skipBytes(num);
//读取num个字节
num = din.read(b);
}
//关闭输入,输出流
din.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}