我的程序:客户端发送一张图片到服务端,服务端接收后发送一条信息给客户端,客户端收到信息后关闭程序,同样服务端也关闭了
(1)出现的问题:1.在服务端一直调不出来while循环,为什么?
2.在客户端因为服务端跳不出循环,导致一直在阻塞状态
客户端程序
package TCP_FileCopy;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TCP_Client {
public static void main(String[] args) throws IOException {
String pathSent="D:\\null_.jpg";
//1.建立端口连接
Socket socket=new Socket(InetAddress.getLocalHost(),8888);
//定义发送的流,一个是输入流,用于读取文件FileInputStream fis=new FileInputStream("D:\\null_.jpg");
// 一个是输出流,用于发送文件 OutputStream ops= socket.getOutputStream();
OutputStream ops= socket.getOutputStream();
FileInputStream fis=new FileInputStream("D:\\null_.jpg");
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(ops);
byte[] bytes=new byte[1024];
int readline;
while((readline= bis.read(bytes))!=-1){
bos.write(bytes,0,readline);
}
bos.flush();
System.out.println("Client发送图片成功!");
//定义一个流用于接收对方发来的字符流图片
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String s= bufferedReader.readLine();
System.out.println(s);
//读完之后关闭所有的流文件
System.out.println("任务完成");
bufferedReader.close();
fis.close();
ops.close();
socket.close();
}
}
服务端程序
package TCP_FileCopy;
import com.sun.corba.se.spi.orbutil.fsm.Input;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TCP_Server {
public static void main(String[] args) throws IOException {
//输出到目标文件的敌方
String s="src\\null2.jpg";
//先建立一个端口
ServerSocket sockets=new ServerSocket(8888);
//建立一个连接
System.out.println("已建立端口,等待连接");
Socket socket=sockets.accept();
//建立字节输入流,用于接收文件。输出流,用于创建文件
InputStream is= socket.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
OutputStream os=new FileOutputStream(s);
BufferedOutputStream bos = new BufferedOutputStream(os);
byte[] bytes=new byte[1024];
int readline;
System.out.println("已接受文件,正在拷贝");
while((readline=bis.read(bytes))!=-1){
bos.write(bytes,0,readline);
}
System.out.println("拷贝成功");
//建立输入流,用于接收服务端发送的文字
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bufferedWriter.write("Server收到图片");
bufferedWriter.newLine();
// bufferedWriter.flush();
// socket.shutdownOutput();
bufferedWriter.close();
//关闭所有的流
os.close();
is.close();
//bufferedWriter.close();
//socket.close();
sockets.close();
}
}