1,TCP的文件上传:
服务端:
- 1.创建服务端
- 同意客户端的连接
- 得到Socket输入流
- 创建文件输出流
- 循环读写数据
- 得到Socket的输出流写数据
- 关闭 ```java public class Tcps {
public static void main(String[] args) throws IOException {
//创建服务端对象 ServerSocket serverSocket = new ServerSocket(8888);
//同意客户端连接 Socket socket = serverSocket.accept();
//创建服务端输入流 InputStream inputStream = socket.getInputStream();
//创建服务端文件(输出)保存流; FileOutputStream fileOutputStream = new FileOutputStream(“G:\xxx.png”);
//新建空数据包接收数据 byte[] bytes = new byte[1024 * 8]; int length; //循环读取数据包的内容,并写入文件的输出流; while ((length = inputStream.read(bytes)) != -1){
fileOutputStream.write(bytes,0,length);
}
//创建输出流: OutputStream outputStream = socket.getOutputStream(); outputStream.write(“finish”.getBytes());
//close outputStream.close(); fileOutputStream.close(); inputStream.close(); socket.close(); serverSocket.close();
}
}
2. **客户端**:
1. 创建客户端
1. 创建文件输入流
1. 得到Socket的输出流
1. 循环读写数据
1. 得到Socket输入流读取数据
1. 关闭资源
```java
public class Tcpc {
public static void main(String[] args) throws IOException {
//创建客户端对象:
Socket socket = new Socket("127.0.0.1", 8888);
//创建客户端输入的文件流;
FileInputStream fileInputStream = new FileInputStream("G:\\xxx\\xxx2.png");
//创建输出流
OutputStream outputStream = socket.getOutputStream();
//新建空数据包
byte[] bytes = new byte[1024 * 8];
int len;
//循环读取文件io传来的数据,并写入向服务端输出的流;
while ((len = fileInputStream.read(bytes)) != -1){
outputStream.write(bytes,0,len);
}
//********
//关闭输出流,以便让服务端的读取停止等待;
socket.shutdownOutput();
//创建输入流
InputStream inputStream = socket.getInputStream();
//新建空数据包
byte[] bytes1 = new byte[1024 * 8];
//获取读取的数据长度
int len2 = inputStream.read(bytes1);
System.out.println("c:"+new String(bytes,0,len2));
//close
inputStream.close();
outputStream.close();
fileInputStream.close();
socket.close();
}
}