如图:客户端与服务端连接不上,服务端处于阻塞状态:
首先,使用FileInputStream流输入文件,使用FileInputStream.read()方法读取文件返回int型(与题无关,加深记忆,总是忘记强转成int);
其次,关于read()方法的介绍:Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available; 表明read()方式是一个阻塞式方法;
解决方法:使用socket.shutdownOutput();关闭数据的输出;
如图:
客户端:
@Test
public void client(){
InetAddress inet = null;
Socket socket = null;
OutputStream os = null;
FileInputStream fis = null;//读入文件
try {
//1.创建Socket
// socket = new Socket(InetAddress.getByName(("127.0.0.1"),9988));
inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet, 9988);
//2.输出流
os = socket.getOutputStream();
//3.输入流
fis = new FileInputStream(new File("程潇.jpg"));
//4.读写过程
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer)) != -1){
os.write(buffer,0,len);
}
//关闭数据的输出
socket.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
} finally {
//5.资源关闭
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务端:
@Test
public void server(){
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
try {
ServerSocket ss = new ServerSocket(9988);
socket = ss.accept();
is = socket.getInputStream();
fos = new FileOutputStream("潇潇子.jpg");
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1){
fos.write(buffer,0,len);
}
System.out.println("潇潇子服务端已收到来自:"+socket.getInetAddress().getHostName()+"的消息");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}