做网络编程的练习,用socket连接 传输文件,目的是把一个文件传到服务端保存下来
测试结果完全正常,文件也传输完成,但是catch捕捉到了异常???!
当运行服务端时候客户端catch报错,当运行客户端时候服务端catch报错 0.0
代码如下
修改了下代码,我把输出换成e.printStackTrace()打印了,还是这样 结果是实现了的,测试通过,但是有捕获到异常
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.junit.Test;
public class 网络编程_上传 {
public static String ClientInteAddress = "127.0.0.1";
public static String str = "9000";
public static String ServerFileAddress = "E:\\111.xls";
public static String ClientFileAddress = "D:\\15916\\下载\\111.xls";
@Test//服务器
public void server() {
ServerSocket sss = null;
Socket sk = null;
InputStream is = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
try {
sss = new ServerSocket(new Integer(str));
sk = sss.accept();
is = sk.getInputStream();
bis = new BufferedInputStream(is);
fos = new FileOutputStream(ServerFileAddress);
int buffi = 0;
byte [] by = new byte[1024];
while ((buffi = bis.read(by)) != -1) {
fos.write(by);
}
fos.close();
bis.close();
sk.close();
sss.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {fos.close();}
if (bis != null) bis.close();
if (sk != null) sk.close();
if (sss != null) sss.close();
} catch (IOException e) {
System.out.println("服务器报错啦!:关闭流出错");
}
}
}
@Test//客户端
public void client() {
Socket sk = null;
OutputStream os = null;
BufferedOutputStream bos = null;
FileInputStream fis = null;
try {
sk = new Socket(InetAddress.getByName(ClientInteAddress), new Integer(str));
os = sk.getOutputStream();
bos = new BufferedOutputStream(os);
fis = new FileInputStream(ClientFileAddress);
int buffi = 0;
byte [] by = new byte[1024];
while ((buffi = fis.read(by)) != -1) {
bos.write(by);
}
fis.close();
bos.close();
sk.close();
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
} finally {
try {
if (sk != null) sk.close();
if (fis != null) fis.close();
if (bos != null) bos.close();
} catch (IOException e) {
System.out.println("客户端报错啦!:关闭流出错");
}
}
}
}