在學校,我們有一個項目,我們必須從服務器向客戶端發送文件。我們遇到的問題是,當我們將文件從服務器傳輸到客戶端時,服務器會關閉連接。這是到目前爲止我們的代碼:在將文件傳輸到客戶端後保持套接字連接處於打開狀態java
客戶:
public static void main(String argv[]) throws Exception {
int port = 8888; //default
if (argv.length
> 0) {
port = Integer.parseInt(argv[0]);
}
Socket clientSocket = new Socket("127.0.0.1", port);
PrintStream outToServer = new PrintStream(
clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
File f = new File("dictionaryPart.txt");
String serverCommand = inFromServer.readLine().toLowerCase();
while (serverCommand != null) {
System.out.println(serverCommand);
switch (serverCommand) {
case "velkommen":
outToServer.println("Hej");
break;
case "file":
f = copy(clientSocket, f);
String matches = CrackerCentralized.checkFile(f);
System.out.println(matches);
outToServer.println(matches);
break;
}
serverCommand = inFromServer.readLine().toLowerCase();
}
}
public static File copy(Socket clientSocket, File f) {
try {
int filesize = 2022386;
int bytesRead;
int currentTot = 0;
byte[] buffer = new byte[filesize];
InputStream is = clientSocket.getInputStream();
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(buffer, 0, buffer.length);
currentTot = bytesRead;
while (bytesRead != -1) {
bytesRead = is.read(buffer, currentTot, (buffer.length - currentTot));
if (bytesRead >= 0) {
currentTot += bytesRead;
}
}
bos.write(buffer, 0, currentTot);
bos.flush();
bos.close();
} catch (IOException ex) {
Logger.getLogger(Master_Slave_Sockets_Client.class.getName()).log(Level.SEVERE, null, ex);
}
return f;
}
服務器:
try {
PrintStream outToClient = new PrintStream(connection.getOutputStream());
OutputStream os = connection.getOutputStream();
BufferedInputStream input = new BufferedInputStream(new FileInputStream(f));
outToClient.println("file");
final byte[] buffer = new byte[(int) f.length()];
input.read(buffer, 0, buffer.length);
os.write(buffer, 0, buffer.length);
os.write(-1);
os.flush();
System.out.println(connection.isClosed());
os.close();
System.out.println(connection.isClosed());
} catch (IOException ex) {
Logger.getLogger(SocketController.class.getName()).log(Level.SEVERE, null, ex);
}
我知道爲什麼連接不斷閉幕。我們通過編寫
output.close();
關閉套接字的輸出,但我不什麼其他的方式,我們必須努力做到這一點,使服務器保持監聽客戶回答(匹配/不匹配)知道,這樣服務器知道它應該發送更多的文件,或者如果客戶端成功..是否可以在不關閉與服務器的連接的情況下發送文件?我在過去的兩天中一直都搜索不到任何東西
感謝您的閱讀和幫助。
我不會,如果它太多,但你可以提供一個如何做到這一點的例子,或者告訴我更多關於它的一點點?我對套接字編程相當陌生,我不確定我是否理解你的意思。 – Ulbo
+1用於確定對應用程序協議的需求。分隔符不是在協議中構造消息的唯一方式,您也可以簡單地在正在傳輸的消息長度的前面加上前綴,以便接收方知道要讀取多少個字節。 – Dev