我想創建小型客戶端服務器TCP文件傳輸程序。我有一件事情有問題。當我從客戶端發送文件到服務器時,例如txt文件:omg.txt,我希望服務器讀取傳入的文件名。Java TCP服務器讀取文件名
所以 - 客戶端發送omg.txt,服務器說「新文件recived:omg.txt」。我試圖使用BufferedReader
(服務器)和DataOutputStream
(客戶端,因爲你必須寫文件的名稱發送它),但它沒有工作。
編輯:
客戶:
Socket sock = new Socket("localhost",13267);
System.out.println("Wait...");
Scanner input = new Scanner(System.in);
while(true){
// wysylanie
System.out.println("Filename");
String p = input.nextLine();
File myFile = new File (p);
boolean exists = (new File(p)).exists();
if (exists) {
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(sock.getOutputStream());
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Wait...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done");
sock.close();
}
服務器:
int filesize=6022386;
int bytesRead;
int current = 0;
ServerSocket servsock = new ServerSocket(13267);
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Wait...");
Socket sock = servsock.accept();
System.out.println("OK : " + sock);
// odbior pliku
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
System.out.println("New filename");
String p = input.nextLine();
File plik = new File(p);
FileOutputStream fos = new FileOutputStream(plik);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(mybytearray, 0 , current);
bos.flush();
System.out.println("File saved");
bos.close();
sock.close();
我試圖做這樣的事情:
客戶端插件:
DataOutputStream outToServer = new DataOutputStream(sock.getOutputStream());
sentence = input.nextLine();
outToServer.writeBytes(sentence);
服務器插件:
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(sock.getInputStream()));
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
...但偏偏我已經 「等等。」 所有的時間爲客戶
到底是什麼問題了嗎?文件名實際上是否完全轉移到服務器上? – miku