我试图读取客户端发送到服务器的路径中的文件内容,服务器正在接收文件路径并读取数据但不知何故,当我发送数据时,我的客户端没有收到它可以你帮助确定我做错了什么 Serverside代码:
ServerSocket myserver = new ServerSocket(5354);
System.out.println("SERVER RUNNING on 127.0.0.1:5354 \n waiting for connection from client...\n");
try {
while (true) {
Socket socket = myserver.accept();
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString() + "Hi there I'm the server,I have recieved your connection");
System.out.println("Received connection from a client:\n"+ socket.getRemoteSocketAddress().toString());
//specify the filename
Scanner input=new Scanner(socket.getInputStream());
String filepath=input.next();
File file=new File(filepath);
FileInputStream fis=new FileInputStream(file);
BufferedInputStream bf=new BufferedInputStream(fis);
//GET socket output stream
BufferedOutputStream outToClient=new BufferedOutputStream(socket.getOutputStream());
byte[] contents=new byte[(int)file.length()];
try{
bf.read(contents,0,contents.length);
outToClient.write(contents,0,contents.length);
outToClient.flush();
String s=new String(contents, StandardCharsets.UTF_8);
out.write(s);
out.flush();
System.out.println(s);
}catch (Exception e){
System.out.println(e.getStackTrace().toString());
}finally{
if(bf!=null)bf.close();
if(outToClient!=null)outToClient.close();
}
//file transfer complete.close the socket or throw an error
} catch(Exception e){
System.out.println("Sorry I got an error" + e.getMessage());
}finally {
socket.close();
}
}
}catch(Exception e){
System.out.println("Oopps smething got messed up " + e.getMessage());
}finally{
myserver.close();
}
}
客户端代码:
int port;
InetAddress ipaddress;
byte[] contents=new byte[1000];
String filepath;
//get input for the server you want to connect to
System.out.print("ENTER THE IP ADDRESS:");
Scanner input = new Scanner(System.in);
ipaddress = InetAddress.getByName(input.next());
System.out.print("ENTER THE PORT NUMBER:");
port = input.nextInt();
System.out.print("enter the name of the file you want to read:");
filepath=input.next();
Socket myclient = new Socket(ipaddress, port);//creating a socket connection to the server
myclient.getOutputStream().write(filepath.getBytes(Charset.forName("UTF-8")));
myclient.getOutputStream().flush();
Scanner sinput = new Scanner(new InputStreamReader((myclient.getInputStream())));
String response = sinput.nextLine();
System.out.print(response);
myclient.getReceiveBufferSize();
myclient.getKeepAlive();
BufferedReader br=new BufferedReader(new InputStreamReader(myclient.getInputStream()));
String data=br.readLine();
System.out.println(data);
myclient.close();
System.out.println("data transmission finished....:)");
}