在发送端,如果我用outputStream传输到服务端是可以的,但是如果用bufferedoutputstream,在服务端就接受不到数据,连接什么都正常。。
发送端数据如下
package com.itheima.javaSE.Internet;
import java.io.*;
import java.net.Socket;
import java.util.Arrays;
public class TCPsend {
public static void main(String[] args) throws IOException {
faild();
}
private static void faild() throws IOException {
//本地的流,将数据写到内存
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\86130\\Desktop\\新建文件夹\\a.txt"));
//网络的流,将数据写到网络
Socket socket = new Socket("127.0.0.1", 10002);
OutputStream os = socket.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
//读取和写入操作
byte[] bytes = new byte[1024];
int len;
while ((len = bis.read(bytes)) != -1) {
System.out.println(bytes);
bos.write(bytes, 0, len);
}
//给服务器一个结束标记
socket.shutdownOutput();
//接收服务器的数据
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
socket.close();
bis.close();
}
}
接收端代码如下
public class TCPreceive {
public static void main(String[] args) throws IOException {
faild();
}
private static void faild() throws IOException {
ServerSocket ss = new ServerSocket(10002);
Socket accept = ss.accept();
//网络中的流
BufferedInputStream bis = new BufferedInputStream(accept.getInputStream());
//本地的流
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\Users\\86130\\Desktop\\新建文件夹\\b.txt"));
byte[] bytes = new byte[1024];
int len;
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
//回信
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));
bw.write("下载完毕!");
bw.newLine();
bw.flush();
accept.close();
ss.close();
bos.close();
}
}
更改后的发送端数据如下(服务端能接受数据)
package com.itheima.javaSE.Internet;
import java.io.*;
import java.net.Socket;
import java.util.Arrays;
public class TCPsend {
public static void main(String[] args) throws IOException {
faild();
}
private static void faild() throws IOException {
//本地的流,将数据写到内存
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\86130\\Desktop\\新建文件夹\\a.txt"));
//网络的流,将数据写到网络
Socket socket = new Socket("127.0.0.1", 10002);
OutputStream os = socket.getOutputStream();
//读取和写入操作
byte[] bytes = new byte[1024];
int len;
while ((len = bis.read(bytes)) != -1) {
System.out.println(bytes);
os.write(bytes, 0, len);
}
//给服务器一个结束标记
socket.shutdownOutput();
//接收服务器的数据
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
socket.close();
bis.close();
}
}