У меня есть следующий код для связи между клиентом и сервером. Я могу запустить клиент и сервер на одной машине. Но если я пытаюсь запустить клиент с другой машины, я не могу запустить. Также мне нужен другой клиент, чтобы эти 2 клиента могли общаться друг с другом через сервер.
Теперь сервер и клиент могут обмениваться данными друг с другом. Но я хочу другого клиента, чтобы только эти 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")));
}