www
客户端:
java
package com.itheima.b03TCPTest3;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws IOException {
System.out.println("===客户端启动===");
//1、创建socket通信管道 请求连接
Socket socket = new Socket(InetAddress.getLocalHost(),10001);
//2、本地IO流将数据输入到内存 使用缓冲流 快
FileInputStream fis = new FileInputStream("/Users/wangjia/Desktop/CS/计算机网络/clientdir/面试算法.png");
BufferedInputStream bfr = new BufferedInputStream(fis);
//3、网络IO流将数据从内存传到网络服务端 字节流输出 所以要通过字节数组按照字节大小逐一传输
OutputStream os = socket.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
int len;
byte[] bytes = new byte[1024];
while((len = bfr.read(bytes)) != -1){
bos.write(bytes,0,len);
}
//4、客户端通知服务器数据传输完毕 通过socket通信管道方法
socket.shutdownOutput();
//5、获取服务端反馈
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg = br.readLine();
System.out.println("服务端反馈信息:" + msg);
//6、释放资源
socket.close(); //socket关闭表示 撤销连接
服务端
java
package com.itheima.b03TCPTest3;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws IOException {
System.out.println("===客户端启动===");
//1、创建socket通信管道 请求连接
Socket socket = new Socket(InetAddress.getLocalHost(),10001);
//2、本地IO流将数据输入到内存 使用缓冲流 快
FileInputStream fis = new FileInputStream("/Users/wangjia/Desktop/CS/计算机网络/clientdir/面试算法.png");
BufferedInputStream bfr = new BufferedInputStream(fis);
//3、网络IO流将数据从内存传到网络服务端 字节流输出 所以要通过字节数组按照字节大小逐一传输
OutputStream os = socket.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
int len;
byte[] bytes = new byte[1024];
while((len = bfr.read(bytes)) != -1){
bos.write(bytes,0,len);
}
//4、客户端通知服务器数据传输完毕 通过socket通信管道方法
socket.shutdownOutput();
//5、获取服务端反馈
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg = br.readLine();
System.out.println("服务端反馈信息:" + msg);
//6、释放资源
socket.close(); //socket关闭表示 撤销连接