要注意的点:
- ServerSocket 和 Socket
- InetAddress 类
- socket.getInputStream() 和 socket.getOutputStream()
- socket.getOutputStream() 这个输出流在完成输出后,需要有一个结束标记,可以用socket.shutdownOutput(),否则会一直等待继续输出
- socket流在最后一起关闭
客户端代码:
public class Client { // 客户端
public static void main(String[] args) throws IOException {
// 创建连接服务端的socket
Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
String path = "d:\\sx.jpg";
// 读取客户端本地文件的输入流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
// 传送文件的socket输出流
OutputStream outputStream = socket.getOutputStream();
int readByte = 0;
byte[] buf = new byte[1024];
// 边读入边输出
while((readByte = bis.read(buf)) != -1 ){
outputStream.write(buf,0,readByte);
}
// socket输出信息完毕后记得 shutdown
// 否则会卡在这
socket.shutdownOutput();
// 接收服务端传来的接收状态的输入流
InputStream inputStream = socket.getInputStream();
while((readByte = inputStream.read(buf)) != -1){
System.out.println(new String(buf,0,readByte));
}
// 闭流
inputStream.close();
outputStream.close();
bis.close();
socket.close();
}
}
服务端代码:
public class Server { //服务端
public static void main(String[] args) throws IOException {
// 创建 serverSocket
ServerSocket serverSocket = new ServerSocket(8888);
// 监听端口
Socket socket = serverSocket.accept();
String path = "d:\\sx2.jpg";
// 创建输出流处理客户端传来的图片
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
// socket输入流
InputStream inputStream = socket.getInputStream();
int readByte = 0;
byte[] buf = new byte[1024];
// 从socket输入流读取图片的字节数组,并同时写入到输出流中
while((readByte = inputStream.read(buf)) != -1) {
bos.write(buf,0,readByte);
}
// 不涉及socket的流,可以提前关闭
bos.close();
// 收到客户端的图片后,给客户端回送消息
OutputStream outputStream = socket.getOutputStream();
outputStream.write("服务端已收到图片".getBytes());
// socket输出信息完毕后记得 shutdown
socket.shutdownOutput();
// 关闭 socket相关的流,都要放最后关闭
outputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
}
}