服务器
设置端口号为9999,开启服务,获得一个客户端的连接。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Servlet {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("文件服务器开启------");
//获得一个客户端的连接
Socket socket = serverSocket.accept();
// String msg = DataUtil.receiveMsg(socket);
// System.out.println(msg);
// FileOutputStream fos=new FileOutputStream("2.txt");
// InputStream is = socket.getInputStream();
// byte[] arr = new byte[100];
// int len;
// while ((len=is.read(arr))>0)
// {
// fos.write(arr);
// System.out.println(len);
// }
DataUtil.receiveFile(socket,"rh.txt");
}
}
客户端
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
//客户端
Socket socket = new Socket("127.0.0.1",9999);
//
// //发送消息到服务器
// DataUtil.sendMsg(socket,"你好");
// FileInputStream fis=new FileInputStream("src/1.txt");
// int len;
// byte b[]=new byte[1024];
// OutputStream os = socket.getOutputStream();
// while ((len=fis.read(b))!=-1)
// {
// os.write(b);
// }
DataUtil.sendFile(socket,"src/1.txt");
}
}
工具类
import java.io.*;
import java.net.Socket;
public class DataUtil {
public static void sendMsg(Socket socket , String msg){
try {
OutputStream os = socket.getOutputStream();
os.write(msg.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public static String receiveMsg(Socket socket){
try {
InputStream is = socket.getInputStream();
byte[] arr = new byte[1024];
int len = is.read(arr);
String msg = new String(arr, 0, len);
return msg;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void sendFile(Socket socket, String filename) {
try {
FileInputStream fis = new FileInputStream(filename);
int len;
byte arr[] = new byte[1024];
OutputStream os = socket.getOutputStream();
while ((len = fis.read(arr)) != -1) {
os.write(arr,0,len);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String receiveFile(Socket socket, String filename){
try {
FileOutputStream fos=new FileOutputStream(filename);
InputStream is = socket.getInputStream();
byte[] arr = new byte[1024];
int len;
while ((len=is.read(arr))!=-1)
{
fos.write(arr,0,len);
}
is.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
a.txt
运行结果
rh.txt