目前我正在尝试通过Java套接字发送文件。我可以成功发送特定文件的请求并获取文件。但是,当我尝试再次执行它而不重新启动程序时,我无法这样做。
这是我的代码:
客户端
System.out.print("What file do you want? ");
name = consoleIn.readLine();
int bytesRead;
if(!name.equals("!")) {
InputStream in = null;
OutputStream output = null;
DataInputStream serverData = null;
while(!name.equals("!")) {
socketOut.println(name);
socketOut.flush();
InputStream is = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
is = socket.getInputStream();
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
try {
fos = new FileOutputStream(name);
bos = new BufferedOutputStream(fos);
} catch (FileNotFoundException ex) {
System.out.println("File not found. ");
}
byte[] bytes = new byte[4000];
int count;
while ((count = is.read(bytes)) != -1) {
bos.write(bytes, 0, count);
}
System.out.println("Here");
bos.flush();
System.out.print("What file do you want? ");
name = consoleIn.readLine();
}
}
服务器
socket = serverSocket.accept();
System.out.println("Connection accepted!");
BufferedReader socketIn =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
//PrintWriter socketOut = new PrintWriter(socket.getOutputStream());
String name;
BufferedReader fileIn;
String line;
name = socketIn.readLine();
System.out.println(name);
while((!name.equals("!")) && (!name.equals("*"))) {
File file = new File(rootDirectory, name);
byte[] bytes = new byte[4000];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
int count;
System.out.println("Sending: " + name);
while ((count = bis.read(bytes)) != -1) {
out.write(bytes, 0, count);
}
out.flush();
System.out.println("Sent");
name = socketIn.readLine();
System.out.println(name);
}
我没有被提示输入我的第二个请求。
答案 0 :(得分:0)
我对FileServer:69
感到好奇 - 您正在接受另一个阻止所有进程的用户套接字。
只需从服务器中删除此行,所有这些都应该有效。
更重要的是,我建议你为每个接受的套接字创建一个新线程。