想着用java的网络编程,客户端先发送文件,服务端接收,客户端在发送一条语句,服务端已接受
但结果是文件没有完全接受(已保存,但是打不开),语句发出去却显示null
服务端代码
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Test_Server {
public static void main(String[] args) throws IOException {
ServerSocket sockets=new ServerSocket(8899);
Socket socket = sockets.accept();
BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
FileOutputStream fileOutputStream = new FileOutputStream("D:\\null2.jpg");
int i=0;
byte[] bytes=new byte[1024];
while((i=bufferedInputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0 ,i);
}
System.out.println("已接受文件");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String s = bufferedReader.readLine();
System.out.println(s);
// BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
// bufferedOutputStream.write("copyRightNow".getBytes());
// bufferedOutputStream.close();
bufferedReader.close();
fileOutputStream.close();
bufferedInputStream.close();
}
}
客户端代码
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Test_Client {
public static void main(String[] args) throws IOException {
Socket socket=new Socket(InetAddress.getLocalHost(),8899);
OutputStream outputStream = socket.getOutputStream();
BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(outputStream);
//
//
byte[] bytes=getBytes();
bufferedOutputStream.write(bytes);
System.out.println("已发送文件");
//发送语句
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write("helloWorld");
bufferedWriter.newLine();
bufferedWriter.flush();
socket.shutdownOutput();
System.out.println("已发送语句");
bufferedWriter.close();
socket.close();
}
//获取二进制文件保存在bytes数组中
public static byte[] getBytes() throws IOException {
File file = new File("D:\\null.jpg");
FileInputStream fileInputStream = new FileInputStream(file);
int len=(int)file.length();
byte[] bytes=new byte[len];
int readLine;
while((readLine= fileInputStream.read(bytes))!=-1){}
fileInputStream.close();
return bytes;
}
}