对象未通过套接字发送

时间:2016-06-02 03:28:53

标签: java sockets object server client

这让我疯了。在包含缓冲图像的对象和尝试将服务器客户端系统实现为游戏更新和每秒渲染60次之间,我完全迷失了。我以为我做的一切都是正确的,所以我隔离了服务器客户端系统,似乎无法通过套接字发送对象。

程序似乎陷入困境,在尝试接收对象时无法继续。

代码捕获的具体位置是:

public class Interfacer{
public static void main(String[] args){
    try {
        Client c = new Client();
        System.out.println("it ran 1/2...client");
        while(true){
            Troops troop2 = (Troops)c.receiveObject();  
            JOptionPane.showMessageDialog(null, troop2.getX());
            System.out.println("it ran...client");
        }
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }
}



}





public class Interfacer2{
public static void main(String[] args){
    try {
        Server s = new Server();
        Troops troop = new Goblin(1,1,1);
        s.sendObject(troop);
        System.out.println("it ran...server");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

public class Client extends JFrame{


private static final long serialVersionUID = 1L;
private ObjectOutputStream output;
private ObjectInputStream input;

private String serverIP;
private Socket connection;

JTextArea t;
JFrame f;

//constructor
public Client(String host){

    serverIP = host;

    f = new JFrame();
    f.getContentPane().setPreferredSize(new Dimension(300, 300));
    f.pack();

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLocationRelativeTo(null);
    t = new JTextArea();
    f.add(t, BorderLayout.CENTER);
    f.setVisible(true);

    try{
        connectToServer();
        setupStreams();
    }catch(EOFException eofException){
        //t.append("Connection was terminated");
    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}

    public Client(){

    serverIP = "127.0.0.1";

    f = new JFrame();
    f.getContentPane().setPreferredSize(new Dimension(300, 300));
    f.pack();

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLocationRelativeTo(null);
    t = new JTextArea();
    f.add(t, BorderLayout.CENTER);
    f.setVisible(true);


    try{
        connectToServer();
        setupStreams();
    }catch(EOFException eofException){
        //t.append("Connection was terminated");
    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}



//connect to server
private void connectToServer() throws IOException{
    t.append("Attempting connection...");
    connection = new Socket(InetAddress.getByName(serverIP), 7382);
    t.append("Connection Established! Connected to: " + connection.getInetAddress().getHostName());
}

//set up streams
private void setupStreams() throws IOException{
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();
    input = new ObjectInputStream(connection.getInputStream());
    t.append(" The streams are now set up!");
}


//Close connection
public void closeConnection(){
    //t.append(" Closing the connection!");
    try{
        output.close();
        input.close();
        connection.close();
    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}

public void sendObject(Object o) throws IOException{
    output.writeObject(o);
    output.flush();
}
public Object receiveObject() throws IOException, ClassNotFoundException{
    return input.readObject();  
}

}


public class Server{



private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;

JTextArea t;
JFrame f;

//constructor
public Server(){


    f = new JFrame();
    f.getContentPane().setPreferredSize(new Dimension(300, 300));
    f.pack();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLocationRelativeTo(null);
    t = new JTextArea();
    f.add(t, BorderLayout.CENTER);
    f.setVisible(true);

    try{
        server = new ServerSocket(7382, 100); //6789 is a dummy port for testing, this can be changed. The 100 is the maximum people waiting to connect.
        while(true){
            try{
                //Trying to connect and have conversation
                waitForConnection();
                setupStreams();
            }catch(EOFException eofException){
                //t.append("Connection was terminated");
            }
        }
    } catch (IOException ioException){
        ioException.printStackTrace();
    }
}

//wait for connection, then display connection information
private void waitForConnection() throws IOException{
    t.append(" Waiting for someone to connect...");
    connection = server.accept();
    t.append(" Now connected to " + connection.getInetAddress().getHostName());
}

//get stream to send and receive data
private void setupStreams() throws IOException{
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();

    input = new ObjectInputStream(connection.getInputStream());

    t.append(" Streams are now setup ");
}


        //  input.readObject();


public void closeConnection(){
    //t.append(" Closing Connections... ");
    try{
        output.close(); //Closes the output path to the client
        input.close(); //Closes the input path to the server, from the client.
        connection.close(); //Closes the connection between you can the client
    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}
public void sendObject(Object o) throws IOException{
    output.writeObject(o);
    output.flush();
}
public Object receiveObject() throws IOException, ClassNotFoundException{
    return input.readObject();  
}

}


public class Troops implements Serializable{
private int x;
private int y;


private int health;
private int movSpeed;
private int movSpeedx;
private int movSpeedy;
private int cost;
private long deployCoolDown;
private int level;
private transient BufferedImage image;
private int size = 16;
/**
 * 
 * @param x
 * @param y
 * @param level
 * @param health
 * @param movSpeed
 * @param movSpeedx
 * @param movSpeedy
 * @param cost
 * @param deployCoolDown
 * @param image
 * 
 */

public Troops(int x, int y, int level, int health, int movSpeed, int movSpeedx, int movSpeedy, int cost, long deployCoolDown, BufferedImage image){
    this.x = x;
    this.y = y;
    this.level = level;
    this.health = health;
    this.movSpeed = movSpeed;
    this.movSpeedx = -movSpeed;
    this.movSpeedy = movSpeedy;
    this.cost = cost;
    this.deployCoolDown = deployCoolDown;
    this.image = image;

}

public int getX() {
    return x;
}
public void setX(int x) {
    this.x = x;
}
public int getY() {
    return y;
}
public void setY(int y) {
    this.y = y;
}
public int getSize(){
    return size;
}
public int getMovSpeed() {
    return movSpeed;
}
public void setMovSpeed(int movSpeed) {
    this.movSpeed = movSpeed;
}
public int getHealth() {
    return health;
}

public void changeHealth(int health) {
    this.health += health;
}

public int getCost() {
    return cost;
}

public void setCost(int cost) {
    this.cost = cost;
}

public long getDeployCoolDown() {
    return deployCoolDown;
}

public void setDeployCoolDown(int deployCoolDown) {
    this.deployCoolDown = deployCoolDown;
}

 private void writeObject(ObjectOutputStream out)throws IOException{
     out.defaultWriteObject();
     //write buff with imageIO to out
 }

 private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{
     in.defaultReadObject();
     //read buff with imageIO from in
 }


}

由System.out.print推断。其余的代码如下,没有抛出任何错误,我运行Interfacer和Interfacer2。

{{1}}

这里是我获得部队类的瞬态和readObject / writeObject部分的地方:

Java - Sending an object that points to a BufferedImage through a Socket

1 个答案:

答案 0 :(得分:0)

Server的构造函数包含while循环,在IOExceptionEOFException以外的Interfacer2之前不会退出,因此您的s.sendObject()类永远无法进入下一行调用if (document.getElementById("name")) {}

设计不佳。构造函数应该构造对象,而不是参与无限循环或网络I / O.