Good day to all. Long ago, Java was not even at this level. I have a knowledge level of JAVA - 0-1 = -1 and in the area of ​​Servers. But there was a task where you need to build a simple chat on JAVA - Client / Server. Everything is fine with the client, GOOGLE collected it)) And the server also collected it. Everything works fine until the user cuts down my written client.

I give the server code

public static void main(String[] args) { new Thread(new Server()).start(); } public void run() { try { server = new ServerSocket(10058,10000); while(true){ connection = server.accept(); System.out.println("Welcome to ISICA SERVER v0.1"); output = new ObjectOutputStream(connection.getOutputStream()); // Слушаем input = new ObjectInputStream(connection.getInputStream()); // Слушаем //JOptionPane.showMessageDialog(null, (String)input.readObject()); System.out.println("Get message: "+input.readObject()); output.writeObject("You send: "+input.readObject()); output.flush(); // Закончить поток } } catch (UnknownHostException e) { // TODO Auto-generated catch block //e.printStackTrace(); // Error } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); // Error // run(); } catch (HeadlessException e) { // TODO Auto-generated catch block //e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block // e.printStackTrace(); } 

And so, when the user disables the client, the server itself is also automatically cut down. How to organize the code so that the Server is not cut down after the client terminates the session, disconnecting the client.

Run on UBUNTU - server. Client on Mac OS.

Here is the client code, if required :)

 public class Client extends JFrame implements Runnable { static private Socket connection; static private ObjectOutputStream output; // Output static private ObjectInputStream input; // Input public static void main(String[] args) { new Thread(new Client("ISICA client v 0.1")).start(); } public Client(String name){ super(name); JFrame frame = new JFrame(name); // setLayout(new FlowLayout()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(700,550); comp(frame.getContentPane()); //frame.setSize(700,550); frame.setBackground(new Color(41, 41, 41)); frame.pack(); frame.setVisible(true); frame.setLocationRelativeTo(null); } public static void comp(Container panel1){ /* Elements */ JButton button = new JButton("Send"); button.setBackground(Color.green); button.setForeground(Color.black); button.setOpaque(true); button.setBorderPainted(false); JTextArea chatArea = new JTextArea("", 15, 100); JTextField message = new JTextField(); message.setOpaque(true); message.addKeyListener(new KeyAdapter(){ public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { sendData(message.getText()); String msg = chatArea.getText()+"\n YOU: "+message.getText(); chatArea.setText(msg); message.setText(""); } } }); button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource()==button){ sendData(message.getText()); message.setText(""); } } }); /* End Elements */ panel1.setLayout(new GridBagLayout()); panel1.setBackground(new Color(41, 41, 41)); GridBagConstraints p1 = new GridBagConstraints(); p1.fill = GridBagConstraints.HORIZONTAL; p1.weightx = 1; p1.gridx = 1; p1.gridy = 1; p1.gridwidth = 2; p1.weighty = 1.0; chatArea.setForeground(Color.green); chatArea.setBackground(Color.black); panel1.add(chatArea, p1); p1.fill = GridBagConstraints.HORIZONTAL; p1.weightx = 2; p1.gridx = 1; p1.weighty = 1.0; p1.gridwidth = 1; p1.gridy = 2; message.setBackground(Color.black); message.setForeground(Color.green); panel1.add(message, p1); p1.fill = GridBagConstraints.HORIZONTAL; p1.weightx = 0.5; p1.weighty = 1.0; p1.gridwidth = 1; p1.gridx = 2; p1.gridy = 2; panel1.add(button, p1); // final JTextField t1 = new JTextField(10); //JButton b1 = new JButton("Connect"); /* b1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource()==b1){ sendData(t1.getText()); } } }); */ } public void run() { try { while(true){ connection = new Socket(InetAddress.getByName("192.168.2.107"), 10058); output = new ObjectOutputStream(connection.getOutputStream()); // Слушаем input = new ObjectInputStream(connection.getInputStream()); // Слушаем //JOptionPane.showMessageDialog(null, (String)input.readObject()); System.out.println((String)input.readObject()); //return input.re; } } catch (UnknownHostException e) { // TODO Auto-generated catch block //e.printStackTrace(); // Error } catch (IOException e) { // TODO Auto-generated catch block //e.printStackTrace(); // Error } catch (HeadlessException e) { // TODO Auto-generated catch block //e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block //e.printStackTrace(); } } private static void sendData(Object obj){ try { output.flush(); output.writeObject(obj); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); } } } 

Thank you very much in advance!

  • Corrected and added. :) - Alex Mixayelovich Sokolov
  • For server static private Socket connection; do not static, and at each Accept make object new - Saidolim
  • If not difficult, you can give an example. On my code or a friend. I will be very grateful. - Alex Mixayelovich Sokolov

1 answer 1

In this case, the program is configured to work with one connection, or in other words - on one stream. In order to solve this problem, you need to implement a multi-threaded application. I once wrote something like that. Here is the project code (a part with timeouts is implemented).
Code example:

 public class ThreadedEchoServer { static final int PORT = 1978; public static void main(String args[]) { ServerSocket serverSocket = null; Socket socket = null; try { serverSocket = new ServerSocket(PORT); } catch (IOException e) { e.printStackTrace(); } while (true) { try { socket = serverSocket.accept(); } catch (IOException e) { System.out.println("I/O error: " + e); } // new threa for a client new EchoThread(socket).start(); } } } 

and

 public class EchoThread extends Thread { protected Socket socket; public EchoThread(Socket clientSocket) { this.socket = clientSocket; } public void run() { InputStream inp = null; BufferedReader brinp = null; DataOutputStream out = null; try { inp = socket.getInputStream(); brinp = new BufferedReader(new InputStreamReader(inp)); out = new DataOutputStream(socket.getOutputStream()); } catch (IOException e) { return; } String line; while (true) { try { line = brinp.readLine(); if ((line == null) || line.equalsIgnoreCase("QUIT")) { socket.close(); return; } else { out.writeBytes(line + "\n\r"); out.flush(); } } catch (IOException e) { e.printStackTrace(); return; } } } } 

Source of

  • Thank you so much for the code above. Already getting acquainted. - Alex Mixayelovich Sokolov
  • I apologize, I don’t understand why, but GitHub has lost the latest versions of the application, so you’ll have to describe the problem in more detail with words. - Vyacheslav Martynenko
  • Our Server must be configured in such a way that when a new client is connected, a separate stream is created for it, through which we will communicate with the client (in your case, we have a 1 to 1 connection). - Vyacheslav Martynenko
  • It is clear, in that case, if not difficult, you could give me some link with an example of a simple server with threads. I'm also looking for a goolge, I just think you can more accurately give me a link to the article because you wrote a code of this type and are already familiar with it. - Alex Mixayelovich Sokolov
  • He gave an example of code from a similar theme, the details are here: stackoverflow.com/questions/10131377/… - Vyacheslav Martynenko