Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/399.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 在ArrayList中存储DataInput/OutputStream后,如何从套接字读取数据?_Java_Sockets - Fatal编程技术网

Java 在ArrayList中存储DataInput/OutputStream后,如何从套接字读取数据?

Java 在ArrayList中存储DataInput/OutputStream后,如何从套接字读取数据?,java,sockets,Java,Sockets,我的程序使用ArrayList为每个客户端存储DataInputStream和DataOutputStream。当我需要从客户端读取数据时数据输入流不起作用。但是DataOutputStream仍然可以正常工作。我怎样才能解决这个问题。谢谢大家 服务器 import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket;

我的程序使用ArrayList为每个客户端存储
DataInputStream
DataOutputStream
。当我需要从客户端读取数据时<代码>数据输入流不起作用。但是
DataOutputStream
仍然可以正常工作。我怎样才能解决这个问题。谢谢大家

服务器

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author hoang
 */
public class Server {
     public static void main(String[] args) {
        final int PORT = 4444;
        boolean stop = false;
        Executor pool = Executors.newFixedThreadPool(20);
        ArrayList<User> listUsers = new ArrayList<>();
        try {
            ServerSocket serverSocket = new ServerSocket(PORT);
            System.out.println("Server start at port " + PORT);
            while (!stop) {
                try {
                    Socket clientSocket = serverSocket.accept();
                    ClientHandler clientHandler = new ClientHandler(clientSocket, listUsers);
                    pool.execute(clientHandler);
                    System.out.println("Connect to server success!");

                } catch (IOException e) {
                    System.out.println("Client Server can not connect to server! " + e);
                }
            }
        } catch (IOException e) {
            System.out.println("Can not create Server Socket! " + e);
        }
    }
}
class ClientHandler implements Runnable{
    private Socket socket;
    private String userConnected;
    private ArrayList<User> listUsers;
    private DataOutputStream dataOut;
    private DataInputStream dataIn;
    
    public ClientHandler() {
    }

    public ClientHandler(Socket socket, ArrayList<User> listUsers) {
        this.socket = socket;
        this.listUsers = listUsers;
    }
    
    @Override
    public void run() {
        try {
            dataOut = new DataOutputStream(socket.getOutputStream());
            dataIn = new DataInputStream(socket.getInputStream());
            while(true){
                String code = dataIn.readUTF();
                switch(code){
                    case "login":{
                        String name = dataIn.readUTF();userConnected = name;
                        System.out.println(name+" login success");
                        listUsers.add(new User(name, dataIn, dataOut));
                    }
                    break;
                    case "invite":{
                        String invited = dataIn.readUTF();
                        for(User user: listUsers){
                            if(user.getName().equals(invited)){
                                DataOutputStream out = user.getDataOut();
                                DataInputStream in = user.getDataIn();
                                System.out.println("Send invitation from "+userConnected +" to "+user.getName());
                                out.writeUTF("invited");
                                out.flush();
                                System.out.println("Send invitation sucess");
                                System.out.println("Waiting client response!!!!");

                                //Can not read data from in(DataInputStream).
                                System.out.println(in.readBoolean());
                            }
                        }
                    }
                    break;
                    default: System.out.println("Code not exist!");
                }
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    }
    
}

用户

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author hoang
 */
public class Server {
     public static void main(String[] args) {
        final int PORT = 4444;
        boolean stop = false;
        Executor pool = Executors.newFixedThreadPool(20);
        ArrayList<User> listUsers = new ArrayList<>();
        try {
            ServerSocket serverSocket = new ServerSocket(PORT);
            System.out.println("Server start at port " + PORT);
            while (!stop) {
                try {
                    Socket clientSocket = serverSocket.accept();
                    ClientHandler clientHandler = new ClientHandler(clientSocket, listUsers);
                    pool.execute(clientHandler);
                    System.out.println("Connect to server success!");

                } catch (IOException e) {
                    System.out.println("Client Server can not connect to server! " + e);
                }
            }
        } catch (IOException e) {
            System.out.println("Can not create Server Socket! " + e);
        }
    }
}
class ClientHandler implements Runnable{
    private Socket socket;
    private String userConnected;
    private ArrayList<User> listUsers;
    private DataOutputStream dataOut;
    private DataInputStream dataIn;
    
    public ClientHandler() {
    }

    public ClientHandler(Socket socket, ArrayList<User> listUsers) {
        this.socket = socket;
        this.listUsers = listUsers;
    }
    
    @Override
    public void run() {
        try {
            dataOut = new DataOutputStream(socket.getOutputStream());
            dataIn = new DataInputStream(socket.getInputStream());
            while(true){
                String code = dataIn.readUTF();
                switch(code){
                    case "login":{
                        String name = dataIn.readUTF();userConnected = name;
                        System.out.println(name+" login success");
                        listUsers.add(new User(name, dataIn, dataOut));
                    }
                    break;
                    case "invite":{
                        String invited = dataIn.readUTF();
                        for(User user: listUsers){
                            if(user.getName().equals(invited)){
                                DataOutputStream out = user.getDataOut();
                                DataInputStream in = user.getDataIn();
                                System.out.println("Send invitation from "+userConnected +" to "+user.getName());
                                out.writeUTF("invited");
                                out.flush();
                                System.out.println("Send invitation sucess");
                                System.out.println("Waiting client response!!!!");

                                //Can not read data from in(DataInputStream).
                                System.out.println(in.readBoolean());
                            }
                        }
                    }
                    break;
                    default: System.out.println("Code not exist!");
                }
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    }
    
}

  • 存储用户名、DataInputStream和DataOutputStream
运行客户端

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author hoang
 */
public class Client implements Runnable {

    private Socket socket;
    private final int PORT = 4444;
    private final String HOST = "localhost";
    private volatile boolean stop;
    
    private DataInputStream dataIn;
    private DataOutputStream dataOut;
    public Client() {
        Thread t = new Thread(this);
        t.start();
    }

    @Override
    public void run() {
        try {
            socket = new Socket(HOST, PORT);
            dataOut = new DataOutputStream(socket.getOutputStream());
            dataIn = new DataInputStream(socket.getInputStream());
            while(true){
                String code = dataIn.readUTF();
                switch(code){
                    case "invited":{
                        System.out.println("Client received question from Server");
                        System.out.println("Client reply to server");
                        dataOut.writeBoolean(true);
                        dataOut.flush();
                        System.out.println("Client reply success");
                    }
                }
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    }
    public void login(String userName){
        try {
            dataOut.writeUTF("login");
            dataOut.flush();
            dataOut.writeUTF(userName);
            dataOut.flush();
        } catch (IOException e) {
            System.out.println(e);
        }
    }
    public void invite(String invitedName){
        try {
            dataOut.writeUTF("invite");
            dataOut.flush();
            dataOut.writeUTF(invitedName);
            dataOut.flush();
        } catch (Exception e) {
        }
    }
}

  • 此JFrame仅包含两个按钮
    login
    invite
    ,用于测试
    客户端
客户1

客户2

public class RunClient extends javax.swing.JFrame {

    /**
     * Creates new form RunClient
     */
    Client client;
    public RunClient() {
        initComponents();
        this.client = new Client();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Login");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Inivte");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(134, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
                    .addComponent(jTextField1))
                .addGap(59, 59, 59)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(25, 25, 25))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(85, 85, 85)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(45, 45, 45)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addContainerGap(124, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        String name = jTextField1.getText();
        client.login(name);
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        String invitedName = jTextField2.getText();
        client.invite(invitedName);
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(RunClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(RunClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(RunClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(RunClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RunClient().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration                   
}
Server start at port 4444
Connect to server success!
Mra login success
Connect to server success!
Mrb login success
Send invitation from Mrb to Mra
Send invitation sucess
Waiting client response!!!!
Client name: Mra
Client received question from Server
Client reply to server
Client reply success
Client name: Mrb