客户端服务器Java套接字

时间:2019-03-26 11:46:13

标签: java sockets

我具有以下用于客户端和服务器之间通信的代码。我可以在同一台机器上运行客户端和服务器。但是,如果我尝试从其他计算机上运行客户端,则无法运行。我还需要另一个客户端,以便这2个客户端可以通过服务器彼此聊天。

现在,服务器和客户端可以相互交换数据。但是我想要另一个客户端,以便只有这两个客户端可以通过服务器在彼此之间交换数据。

Client.java

public class Clin extends JFrame{
private JLabel statuslabel,chatlabel,instruction,instruction1;
private JTextArea statusarea;
private JPanel chatbox;
private JScrollPane statusscroll;
private JButton Embed,Send,Decode;
private Socket connection;
private ObjectInputStream input;
private ObjectOutputStream output;
private JCheckBox []checks;
private BufferedImage[] images;
private ButtonGroup grp;
private String ServerIP;
public BufferedImage Bufim;
public Clin cli;
public JLabel setlabel;
private int JC;    
private String security=null;

public Clin(String host){
    super("Client");
    Bufim=null;
    cli=this;
    JC=-1;       
    ServerIP=host;
    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setBounds(720,20,700,700);
    this.setResizable(false);   
    this.setLayout(null);
    this.getContentPane().setBackground(Color.RED);



public static void main(String[] args) throws InterruptedException, 
InvocationTargetException {
    Clin cli=new Clin("localhost");
    cli.startRunning();

}

public void startRunning(){//////////////////////////////
    try{
        connectToServer();
        setupStreams();
        whileChatting();
    }catch(EOFException eofException){
        showMessage("\nClient terminated the connection");
    }catch(IOException ioException){
        ioException.printStackTrace();
    }finally{
        closeConnection();
    }
}
private void connectToServer() throws IOException{
    showMessage("\nAttempting connection...");
    connection = new Socket(InetAddress.getByName(ServerIP), 7777);
    showMessage("\nConnection Established! Connected to: " + 
 connection.getInetAddress().getHostName());
}
private void setupStreams() throws 
IOException{//////////////////////////////////////////////////
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();

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

    showMessage("\nStreams are now setup");
}
private void whileChatting() throws 
IOException{///////////////////////////////////
        ableToSend(true);
        Object mess=null;
        try {
            showMessage("\n" + (String)input.readObject());
            security=JOptionPane.showInputDialog(this,"Hey Client please 
provide the OTP you just recieved!");
            if(security==null){
                security="-";
            }
            sendMessage(security);
            String rs=(String)input.readObject();
            showMessage("\n" + ((rs.equals("CLOSE"))?"":rs));
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Clin.class.getName()).log(Level.SEVERE, 
null, ex);
        }
    do{
        try{
            mess =input.readObject();
                            if(mess instanceof String){
                                if(!((String)mess).equals("CLOSE"))
                                    showMessage("\n" + mess);
                            }
                            else {
                                ByteArrayInputStream bin=new 
 ByteArrayInputStream((byte[]) mess);
                                BufferedImage ms=ImageIO.read(bin);
                                displayMessage(ms);
                                bin.close();  
                            }
        }catch(Exception Ex){
            showMessage("\nThe server has sent an unknown object!");
        }
    }while(mess instanceof byte[]||(mess!=null&&! 
((String)mess).equals("CLOSE")));
}

server.java

 public class Serv extends JFrame{
 private JLabel statuslabel,chatlabel,instruction,instruction1;
 private JTextArea statusarea;
 private JPanel chatbox;
 private JScrollPane statusscroll,scroll;
 private JButton Embed,Send,Decode;
 private ServerSocket server;
 private Socket connection;
 private ObjectInputStream input;
 private ObjectOutputStream output;
 private JCheckBox []checks;
 private BufferedImage[] images;
 private ButtonGroup grp;
 public BufferedImage Bufim;
 public Serv sser;
 public JLabel setlabel;
 private int JC;
 private String security=null;

 public Serv(){
    super("Server");
    Bufim=null;
    sser=this;
    JC=-1;
    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setBounds(10,20,700,700);
    this.setResizable(false);   
    this.setLayout(null);
    this.getContentPane().setBackground(Color.RED);


    public static void main(String[] args) throws InterruptedException, 
    InvocationTargetException {
    Serv ser=new Serv();
    ser.startRunning();

    }

    public void startRunning(){//////////////////////////////
        try{
            server = new ServerSocket(7777,100);
                while(true){
                        try{
                                waitForConnection();
                                setupStreams();
                                whileChatting();
            }catch(Exception eofException){
                showMessage("\nServer ended the connection!");
            } finally{
                closeConnection();
            }
        }
    } catch (IOException ioException){
        ioException.printStackTrace();
    }
   }
    private void waitForConnection() throws 
   IOException{/////////////////////////////////////
    showMessage("\nWaiting for someone to connect...");
    connection = server.accept();
    showMessage("\nNow connected to " + 
    connection.getInetAddress().getHostName());
    }
    private void setupStreams() throws 
    IOException{//////////////////////////////////////////////////
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();

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

    showMessage("\nStreams are now setup");
   }
   private void whileChatting() throws 
  IOException{///////////////////////////////////
        chatbox.removeAll();
        this.repaint();
        this.validate();            
           String s=JOptionPane.showInputDialog(this,"Hey Server please 
set the OTP for Client!");
            if(s.equals("")){
                s="12345";
            }
            double dd;
            while((dd=Math.random())<0.1){}
            Integer xx=(int)(dd*100000);
            //String s=xx.toString();
            security=s;
    String message = " You are now connected!\n Your OTP : "+s;
    sendMessage(message);
        try {
            String ss=(String)input.readObject();
            if(!ss.equals(security)){
                sendMessage("Incorrect OTP !");
                return;
            }
            else sendMessage("Verification Successfull !");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Clin.class.getName()).log(Level.SEVERE, 
null, ex);
        }                
    ableToSend(true);
            Object mess=null;
    do{
        try{
            mess =input.readObject();
                            if(mess instanceof String){
                                if(!((String)mess).equals("CLOSE"))
                                    showMessage("\n" + mess);
                            }
                            else {
                                ByteArrayInputStream bin=new ByteArrayInputStream((byte[]) mess);
                                BufferedImage ms=ImageIO.read(bin);
                                displayMessage(ms);
                                bin.close();
                            }
        }catch(Exception Ex){
            showMessage("\nThe user has sent an unknown object!");
        }
    }while(mess instanceof byte[]||(mess!=null&&!((String)mess).equals("CLOSE")));
}

0 个答案:

没有答案