文章目录
服务器端的步骤
1、获取一个连接地址和指定的端口号
2. 等待着客户端的链接
3.读取客户端的消息。输入流
4.文件输出
5.通知客户端接受完毕
6.关闭资源
客户端的步骤
1.获取服务器的地址,端口号
2.创建socket连接获取网络字节输出流
3. 读取需要上传的文件
4. 将读取的文件写出,使用字节流
5. 通知服务器,请求已经结束了
6. 通知服务器接受完毕,断开连接
7. 关闭资源
Java代码实现
服务器:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @description:文件读取的服务器
* @return
*/
public class ServerFile {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket accept = null;
InputStream is = null;
FileOutputStream fos = null;
OutputStream outputStream = null;
try {
//1、获取一个连接地址和指定的端口号
serverSocket = new ServerSocket(9900);
//2. 等待着客户端的链接
accept = serverSocket.accept();
//3.读取客户端的消息。输入流
is = accept.getInputStream();
//4.文件输出
fos = new FileOutputStream(new File("tests.jpg"));
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
//5.通知客户端接受完毕
outputStream = accept.getOutputStream();
outputStream.write("接受完毕,可以关闭连接了".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
//6.关闭资源
if (outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
//关闭输入流
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (accept != null) {
try {
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
客户端:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @description:文件读取的客户端
* @return
*/
public class ClientFile {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
FileInputStream fis = null;
InputStream fis2 = null;
ByteArrayOutputStream baos = null;
try {
//1.获取服务器的地址,端口号
socket = new Socket("127.0.0.1", 9900);
// 2.创建socket连接获取网络字节输出流
os = socket.getOutputStream();
// 3、读取需要上传的文件
fis = new FileInputStream(new File("6.jpg"));
//4. 将读取的文件写出,使用字节流
byte[] bytes = new byte[1024];
int len;
while ((len = fis.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
//5.通知服务器,我的请求已经结束了,不然会一直等待
socket.shutdownOutput();
//6.通知服务器接受完毕,断开连接
fis2 = socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] bytes2 = new byte[1024];
int len2;
while ((len2=fis2.read(bytes2))!= -1){
baos.write(bytes2,0,len2);
}
System.out.println(baos.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4.关闭资源
if (baos != null){
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
先启动服务器,然后启动客户端,服务器就可以接受到数据。
结果:
客户端:
服务器:
文件的结果: