最近在学习TCP连接的时候,狠狠的被DataStream坑了一把
1、.close()方法会导致Socket的关闭
我们经常习惯这么写:
Socket mySocket = ss.accept();
DataInputStream dis = new DataInputStream(mySocket.getInputStream());
DataOutputStream dos = new DataOutputStream(mySocket.getOutputStream());
某段程序使用完了之后,就dos.close();
如果下面还需要数据传输,那么就会抛出Socket is closed异常。。。喜闻乐见
2、s.shutdownOutput();可以帮助关闭流,但是怎么开起来,求解中
3、RandomAccessFile 类,包装了DataInputStream/DataOutputStream,一个简单用法
file_name = dis.readUTF();
System.out.println("当前file_name为" + file_name);
Path = ServerFilePath + file_name;
System.out.println("当前服务器接收端路径为" + ServerFilePath + file_name);
File file = new File(Path);
file.createNewFile();
RandomAccessFile raf = new RandomAccessFile(file, "rw");
byte[] buf = new byte[20480];
int num;
while ((num = dis.read(buf)) != -1) {
<span style="white-space:pre"> </span>raf.write(buf, 0, num);
<span style="white-space:pre"> </span>raf.skipBytes(num);
}
raf.close();