我正在使用jsp
开发一个Web应用程序,其中我使用tcp connection
将文件从服务器发送到客户端。但在这样做时,程序进入无限循环。
它没有返回任何东西。有人可以帮帮我吗?
我在这里发布服务器和客户端代码。
服务器代码:
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
sendData = "FILE".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 5006);
clientSocket.send(sendPacket);
sendData = file.getBytes();
sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 5006);
clientSocket.send(sendPacket);
ServerSocket serverSocket = new ServerSocket(5494);
Socket socket = serverSocket.accept();
File transferFile = new File("C:\\Users\\Krishna\\Documents\\LanMan\\" + file);
byte[] bytearray = new byte[(int) transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray, 0, bytearray.length);
OutputStream os = socket.getOutputStream();
os.write(bytearray, 0, bytearray.length);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String a = (new String(receiveData, "UTF-8")).trim();
//if(a.equals())
os.flush();
//bin.close();
socket.close();
serverSocket.close();
客户代码:
if (a.startsWith("FILE")) {
byte b[] = new byte[1024];
received = new DatagramPacket(receiveData, receiveData.length);
serversocket.receive(received);
a = (new String(receiveData, "UTF-8")).trim();
int filesize = 2022386;
int bytesRead;
int currentTot = 0;
socket = new Socket(ip, 5494);
byte[] bytearray = new byte[filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\LanMan\\" + a);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray, 0, bytearray.length);
currentTot = bytesRead;
do {
bytesRead = is.read(bytearray, currentTot, (bytearray.length - currentTot));
if (bytesRead >= 0) currentTot += bytesRead;
} while (bytesRead > -1);
bos.write(bytearray, 0, currentTot);
bos.flush();
bos.close();
//fos.close();
//is.close();
sendData = "OK".getBytes();
DatagramPacket send = new DatagramPacket(sendData, sendData.length, ip, port);
serversocket.send(send);
socket.close();
}
答案 0 :(得分:0)
您实施了死锁。
服务器写入文件内容,然后等待来自客户端的数据报包,关闭套接字。
客户端读取,直到服务器关闭套接字,然后发送数据报包。
所以各方都在等待另一方。
此外,永远不要忽略InputStream.read()方法的结果,就像在服务器代码中一样。您永远不能假设所有文件都将在一次调用中被读取。