Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 读取流套接字服务器_Java_Sockets_Serialization_Tcp - Fatal编程技术网

Java 读取流套接字服务器

Java 读取流套接字服务器,java,sockets,serialization,tcp,Java,Sockets,Serialization,Tcp,由于我将字符串拆分到客户机菜单,我的程序就变成了bug,因为swicth在客户机上不做任何事情,也不启动任何方法,这就是为什么当服务器获得输出并启动下载文件时,当它开始编写客户机时,它不会接受它,因为他的菜单没有启动接收功能,有没有提示让交换机和服务器工作以及同步的方法?客户端实体在服务器上传时发送文件,客户端实体在服务器下载时接收文件 cli输入的所有cuz 这是我的conexion服务器 package eagz.org; import java.io.BufferedInputStrea

由于我将字符串拆分到客户机菜单,我的程序就变成了bug,因为swicth在客户机上不做任何事情,也不启动任何方法,这就是为什么当服务器获得输出并启动下载文件时,当它开始编写客户机时,它不会接受它,因为他的菜单没有启动接收功能,有没有提示让交换机和服务器工作以及同步的方法?客户端实体在服务器上传时发送文件,客户端实体在服务器下载时接收文件 cli输入的所有cuz

这是我的conexion服务器

package eagz.org;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ConexionServer1 extends Thread{
private static ServerSocket ss;
private static Socket s = null;
public static String path = "C:\\Users\\Eduardo\\Desktop\\Eduardo\\Uru\\Clases Programacion\\POO\\CLI\\server\\";
static Scanner input = new Scanner (System.in);
private static BufferedReader in = null;

    ConexionServer1(Socket s){
        this.s = s; }

    public void run(){
        try{
            menu(); } //line 33
        finally{
                try {
                    s.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }   } }



    public static void menu() {
        try {
            while(true){
            ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); // line 47
            ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); 
            String msg = (String)ois.readObject();
            System.out.println(msg);
            String[] cmds = msg.split(" ");
        /*  in = new BufferedReader(new InputStreamReader(
                    s.getInputStream()));
            String clientSelection = in.readLine();
            String[] cmds = clientSelection.split(" ");
            String[] cmds = clientSelection.split("");*/    
            switch(cmds[0]){
            case "create":  ;
            File f = new File(cmds[1]);
                if(!f.exists()){
                    create(cmds[1]);
                    oos.writeObject(">> File Created"); }
                else{
                    create(cmds[1]);
                    oos.writeObject(">> File not created"); }
                break;

            case "delete":
                File f1 = new File(cmds[1]);
                    delete(cmds[1]);
                    if(!f1.exists()){
                        oos.writeObject(" File Deleted ");  }   
                    else{
                        oos.writeObject(" File not found"); }
                break;

            case "download":
                download(cmds[1]);
                oos.writeObject("Sucess");
                break;

            case "upload":
                upload(cmds[1]);
                oos.writeObject("Sucessfull");
                break;

            default:
                System.out.println("Undefined Operation");
                oos.writeObject("Undefined Operation");
                break;
            }//case
        oos.close();
        ois.close();
            }}
         catch (IOException | ClassNotFoundException e) {       e.printStackTrace();    }
    }


    public static void create (String filename){
        File f = new File(path + filename);
        try{if(!f.exists()){
            f.createNewFile();
            System.out.println(">> File Created");              
        }
        else {
            System.err.println(">> File Already Exists");   }
        } 
        catch(Exception e){e.printStackTrace();}
    }//create


    public static void delete (String filename){
        File f = new File(path + filename);
        try{if(f.exists()){
            f.delete();
            System.out.println(">>File Deleted");   }
        else{
            System.err.println(">>Error, File doesnt exist's"); }
        }
        catch(Exception e){e.printStackTrace();}
    }

    public static void upload (String filename){
        File f = new File(path + filename);
        try{
            DataInputStream clientData = new DataInputStream(s.getInputStream());
        //    String fileName = clientData.readUTF();
            OutputStream os = new FileOutputStream(("received from client -> " + f));
            long size = clientData.readLong();
            byte[] buffer = new byte[1024];
            int i = clientData.read(buffer,0,(int) size);
                while(size > 0 && (i) > 0){
                    os.write(buffer, 0, i);
                    size -= i;
                }
            os.flush();
            clientData.close();

     System.out.println("File "+filename+" received from client.");
    }       catch (IOException ex) {
        System.err.println("Client error. Connection closed.");}
}



    public static void download (String filename){
         try {
               File myFile = new File(path + filename);
               byte[] mybytearray = new byte[(int) myFile.length()];
               FileInputStream fis = new FileInputStream(myFile);
               BufferedInputStream bis = new BufferedInputStream(fis);
               DataInputStream dis = new DataInputStream(bis);
               dis.readFully(mybytearray, 0, mybytearray.length);
               OutputStream os = s.getOutputStream();
               DataOutputStream dos = new DataOutputStream(os);
               dos.writeUTF(myFile.getName());
               dos.writeLong(mybytearray.length);
               dos.write(mybytearray, 0, mybytearray.length);
               dos.flush();
               System.out.println("File "+ filename +" sent to client.");
           } catch (Exception e) {
               System.err.println("File does not exist!");
           }    
    }
}
这是我的客户端类

package eagz.org;


public class Cliente {
public static String path = "C:\\Users\\Eduardo\\Desktop\\Eduardo\\Uru\\Clases Programacion\\POO\\CLI\\cliente";
private static Socket s;
private static String fileName;
private static BufferedReader stdin;
private static PrintStream os;
static int PORT = 9000;
static String IP = "localhost"; //use your ip
static Scanner input = new Scanner (System.in);

public static void main(String[] args) throws IOException {
    try {
        s = new Socket(IP ,PORT);
        stdin = new BufferedReader(new InputStreamReader(System.in));

        System.err.println("-- Client  --");
        System.out.println("Connecting to Server ->" +  IP  + "/" + PORT);
        System.out.println("Commands: "+" -> Create "+" -> Delete "+" -> Download "+" -> Upload");
        System.out.println("C:>");

        String inp = input.nextLine();
        String [] cmds = inp.split("");

        ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
        oos.writeObject(inp);

        ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
    //  System.out.println("From Server : " + servermsg);

            switch (cmds[0]) {
                    case "upload":
           //  os.println(cmds);
                        //oos.writeObject(inp);
                        sendFile(cmds[1]);

                        break;
                    case "download":
                        //System.err.print("Enter file name: ");
                        fileName = cmds[1];
                        oos.writeObject(cmds[0] + fileName);
                        receiveFile(fileName);
                        break;
                }   
            //String servermsg = (String) ois.readObject();
            System.out.println("From Server : " );
        } catch (Exception e) { 
            e.printStackTrace();
    }
}


public synchronized  static void sendFile(String fileName) {
    try {
        File myFile = new File(path + fileName);
        byte[] mybytearray = new byte[(int) myFile.length()];
        FileInputStream fis = new FileInputStream(myFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        DataInputStream dis = new DataInputStream(bis);
        dis.readFully(mybytearray, 0, mybytearray.length);
        OutputStream os = s.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeUTF(myFile.getName());
        dos.writeLong(mybytearray.length);
        dos.write(mybytearray, 0, mybytearray.length);
        dos.flush();
        System.out.println("File "+fileName+" sent to Server.");
    } catch (Exception e) {
        System.err.println("File does not exist!");
    }
}

public synchronized static void receiveFile(String fileName) {
    try {
        File f = new File(path + fileName);
        InputStream is = s.getInputStream();
        DataInputStream clientData = new DataInputStream(is);
        fileName = clientData.readUTF();
        OutputStream os = new FileOutputStream(("received from server -> " + f));
        long size = clientData.readLong();
        byte[] buffer = new byte[1024];

        int i = clientData.read(buffer,0,(int) size);
            while (size > 0 && (i) != -1) {
                os.write(buffer, 0, i);
                size -= i;
            }
        os.close();
        clientData.close();
        System.out.println("File "+fileName+" received from Server.");
    } catch (Exception e) {   
        e.printStackTrace();
    }
}
}
这是我的服务器

package eagz.org;


public class Server extends Thread {
public static final int PORT = 9000;
public static ServerSocket ss = null; 
public static Socket s = null;

public static void main(String[] args) {
    try {
        ss = new ServerSocket(PORT);
        System.err.println("- -  Server - -");
        while(true){
            s = ss.accept();
            System.out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
            System.out.println("NEW CONNECTION WORKING ON ADDRESS -> " + s.getInetAddress().getHostName());
            Thread conect = new ConexionServer1(s);
            conect.start();
        }
    } catch (IOException e) {   
        System.err.println("Port already in use.");
        e.printStackTrace();}

    finally{
        try {
            s.close();
            ss.close();
        } catch (Exception e) { e.printStackTrace();    }
    }
}
}
这是我的错误

NEW CONNECTION WORKING ON ADDRESS -> Eduardo
download cesar.txt
java.net.SocketException: Socket is closed
File cesar.txt sent to client.
at java.net.Socket.getOutputStream(Socket.java:943)
at eagz.org.ConexionServer1.menu(ConexionServer1.java:47)
at eagz.org.ConexionServer1.run(ConexionServer1.java:33)

关闭一个套接字的输入或输出流将关闭另一个流和套接字,您将在多个点执行此操作

但是,此代码还有许多其他问题

  • 您将其描述为FTP服务器,但您使用的是Java序列化,这是一种不同的协议。它不是FTP服务器
  • 每次阅读下一条消息时,您都在创建新的对象流,而不是在套接字的生命周期中保留它们。这将导致或类似的结果
  • 您在同一个套接字上混合了
    ObjectInputStream
    DataInputStream
    。这是行不通的
  • 您正在忽略由
    File.delete()
    返回的
    布尔值,并且您正在捕获一个不存在的
    异常
    ,该异常除了NPE或其他编程错误外,无法以相同的方法抛出
  • 当异常应该报告给对等方时,您正在捕获、记录和忽略异常
  • 您假设文件大小适合int
  • 您假设要下载的文件适合内存,而当您可以一次复制一个小缓冲区(比如8192字节)时,就不需要这样做了
  • 您的
    receiveFile()
    方法可能会覆盖接收到的数据。有关在保持连接打开的同时传输多个文件甚至一个文件的正确方法,请参阅

  • 关闭一个套接字的输入或输出流将关闭另一个流和套接字,您将在多个点执行此操作

    但是,此代码还有许多其他问题

  • 您将其描述为FTP服务器,但您使用的是Java序列化,这是一种不同的协议。它不是FTP服务器
  • 每次阅读下一条消息时,您都在创建新的对象流,而不是在套接字的生命周期中保留它们。这将导致或类似的结果
  • 您在同一个套接字上混合了
    ObjectInputStream
    DataInputStream
    。这是行不通的
  • 您正在忽略由
    File.delete()
    返回的
    布尔值,并且您正在捕获一个不存在的
    异常
    ,该异常除了NPE或其他编程错误外,无法以相同的方法抛出
  • 当异常应该报告给对等方时,您正在捕获、记录和忽略异常
  • 您假设文件大小适合int
  • 您假设要下载的文件适合内存,而当您可以一次复制一个小缓冲区(比如8192字节)时,就不需要这样做了
  • 您的
    receiveFile()
    方法可能会覆盖接收到的数据。有关在保持连接打开的同时传输多个文件甚至一个文件的正确方法,请参阅