现在我有客户端和服务端两个程序,
客户端发送文件给服务端
代码如下:
发送:
Java code
-
public
void
SendFile(String fileType,String filePath,Socket socketHandler)
throws
IOException
{
DataInputStream fileInputStream
=
new
DataInputStream(
new
BufferedInputStream(
new
FileInputStream(filePath)));
DataOutputStream fileOutStream
=
new
DataOutputStream(socketHandler.getOutputStream());
int
bufferSize
=
8192
;
byte
[] buf
=
new
byte
[bufferSize];
while
(
true
)
{
int
read
=
0
;
if
(fileInputStream
!=
null
)
{
read
=
fileInputStream.read(buf);
}
if
(read
==-
1
)
{
break
;
}
fileOutStream.write(buf,
0
, read);
}
fileOutStream.flush();
fileInputStream.close();
//
socketHandler.close();
接收:
Java code
-
public
void
ReceiveFile(String fileSavePath,Socket socketHandler,String fileType,String fileName,
int
fileLength,
boolean
isUpload)
throws
IOException
{
String filePureName
=
""
;
long
len
=
0
;
int
bufferSize
=
8192
;
byte
[] buf
=
new
byte
[bufferSize];
if
(fileName.lastIndexOf(
"
//
"
)
>
0
)
{
filePureName
=
fileName.substring(fileName.lastIndexOf(
"
//
"
)
+
1
);
}
else
if
(fileName.lastIndexOf(
"
/
"
)
>
0
)
{
filePureName
=
fileName.substring(fileName.lastIndexOf(
"
/
"
)
+
1
);
}
else
{
filePureName
=
fileName;
}
fileSavePath
+=
filePureName;
DataOutputStream fileOut
=
new
DataOutputStream(
new
BufferedOutputStream(
new
BufferedOutputStream(
new
FileOutputStream(fileSavePath))));
DataInputStream inputStream
=
new
DataInputStream(
new
BufferedInputStream(socketHandler.getInputStream()));
while
(
true
)
{
int
read
=
0
;
if
(inputStream
!=
null
)
{
read
=
inputStream.read(buf);
}
len
+=
read;
fileOut.write(buf,
0
, read);
if
(read
==
-
1
||
fileLength
==
len) {
break
;
}
}
fileOut.flush();
fileOut.close();
}
现在情况是这样的,一般来说发送端第一次链接服务端的时候,可以正常接收文件,但是第二次就会死锁刀: 接收方法里面 的 read = inputStream.read(buf);这句话中
我看网上有很多是说发送端要close socket,但是我close 发送端的socket后,接收端read = inputStream.read(buf);这句话就读不出东西了,read 始终等于-1
请高手指点下。 你每次都新建一个会话 用完关闭 死锁的确是个问题 会不会是程序上逻辑的问题啊 您能不能告诉我怎么建一个新会话呢?
逻辑我觉得不会有问题吧,因为如果客户端和服务端交互简单的字符串一类的东西,完全没有问题,只有传文件有问题。只能传一次。。第二次就死锁。。我每次交互完(每发一个命令,到命令结束)服务端和客户端的 socket都关闭。 来源:足球直播
|