我越是逃离,却越是靠近你。
我越是背过脸,却越是看见你。
我从你开始,
我在你结束。
需求:实现局域网下socket传输文件.
客户端步骤:
1、建立与服务器的连接
2、创建client输出流
3、创建输入流,绑定本地文件
4、读取文件后输出给服务器
服务器端步骤:
1、启动服务器
2、创建accept输入流
3、创建输出流绑定本地文件
4、读取客户端信息写入本地文件
1.字节流传输文件.
public class Client { public static void main(String[] args) throws IOException {
Socket client = new Socket("192.168.0.112", );
OutputStream os = client.getOutputStream();
FileInputStream fis = new FileInputStream("/home/yanshaochen/public/2017-05-06 15-12-02屏幕截图.png");
byte[] bytes = new byte[];
int data;
while((data = fis.read(bytes))!= -){
os.write(bytes, , data);
}
fis.close();
client.close();
System.out.println("发送成功!");
}
}
public class Server { public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket();
System.out.println("listening..");
Socket accept = server.accept();
InputStream is = accept.getInputStream();
FileOutputStream fos = new FileOutputStream("d:\\download\\屏幕截图.png");
byte[] bytes = new byte[];
int data;
while((data = is.read(bytes))!=-){
fos.write(bytes, , data);
}
fos.close();
server.close();
}
2.字符流传输文件txt.
public class Client { public static void main(String[] args) throws IOException { Socket client = new Socket("192.168.0.112", );
OutputStream os = client.getOutputStream();
Reader fr = new FileReader("/home/yanshaochen/public/zfsm.txt");
BufferedReader br = new BufferedReader(fr);
String buffer;
while((buffer = br.readLine())!= null){
buffer += "\r\n";
os.write(buffer.getBytes());
}
br.close();
client.close();
System.out.println("发送成功!");
}
}
public class Server { public static void main(String[] args) throws Exception { ServerSocket server = new ServerSocket();
System.out.println("listening..");
Socket accept = server.accept();
InputStream is = accept.getInputStream();
FileWriter fw = new FileWriter("d:\\download\\zfsm.txt");
byte[] bytes = new byte[];
int data;
while((data = is.read(bytes)) != -){
fw.write(new String(bytes, , data));
}
fw.close();
server.close();
} }