Java socket programming

Joined
Dec 30, 2017
Messages
1
Reaction score
0
I am trying to program a chat application between server and client using sockets.
I followed some tutorials and tried to modify. However, the code does not seem to work.
I am trying to get the port number from a text field when the connect button is clicked and establish the connection. After the button is clicked the button does not work and the program goes into infinite loop.
Can anyone help??
Here is the code:
For server:

Java:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Server extends JFrame{
   public JFrame frame;
   public JButton sendJButton;
   public JPanel main;
   public JPanel right;
   public JPanel panel;
   private JScrollPane pane;
   private Container window;
   private JTextField userText;
   private JTextArea chatWindow;
   private ObjectOutputStream output;
   private ObjectInputStream input;
   private ServerSocket server;
   private Socket connection;
   private JTextField port;
   private JLabel portLabel;
   private JLabel chooseServer;
   private JLabel ip;
   private JTextField ipAdd;
   public static int portNum;
   public JButton connect;
  
   public Server() {
       super("Server");
       frame= new JFrame();
       frame.setSize(600,550);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      
       panel=new JPanel();
       main=new JPanel();
       right=new JPanel();
      
       String choice[]={"TCP","UDP"};

       final JComboBox<String> opt = new JComboBox<String>(choice);
       opt.setVisible(true);
      
       sendJButton=new JButton("Send");
       connect=new JButton("Connect");
      
       userText=new JTextField();
       chatWindow=new JTextArea();
       port=new JTextField();
       chooseServer=new JLabel("Server:");
       ip=new JLabel("IP Address");
       ipAdd=new JTextField();
      
       portLabel=new JLabel("Port:");
      
       pane=new JScrollPane(chatWindow);
      
       panel.setPreferredSize(new Dimension(600, 550));
       main.setPreferredSize(new Dimension(450, 550));
       right.setPreferredSize(new Dimension(150, 550));
      
       main.setLayout(null);
       right.setLayout(null);
      
       pane.setBounds(5,5,400,380);
       userText.setBounds(5,400,400,40);
       sendJButton.setBounds(150,460,80,30);
       portLabel.setBounds(15, 90, 30, 30);
       port.setBounds(50,95,70,25);
       chooseServer.setBounds(15,160,42,25);
       opt.setBounds(60,160,70,25);
       ip.setBounds(40,212,100,25);
       ipAdd.setBounds(15,240,110,25);
       connect.setBounds(22,280,100,25);
      
       userText.setEditable(false);
       userText.addActionListener(
               new ActionListener() {
                  
                   @Override
                   public void actionPerformed(ActionEvent event) {
                       // TODO Auto-generated method stub
                       sendMessage(event.getActionCommand());
                       userText.setText("");
                   }
               }
       );
      
       panel.setLayout(new BorderLayout());
       panel.add(main, BorderLayout.WEST);
       panel.add(right, BorderLayout.EAST);
      
       main.add(userText);
       main.add(pane);
       main.add(sendJButton);
      
       right.add(portLabel);
       right.add(port);
       right.add(chooseServer);
       right.add(opt);
       right.add(ip);
       right.add(ipAdd);
       right.add(connect);
      
       frame.add(panel);
       frame.setTitle("Server");
       frame.setVisible(true);
      
       connect.addActionListener(new ActionListener() {
          
           @Override
           public void actionPerformed(ActionEvent e) {
               // TODO Auto-generated method stub
               setPort();
               startRunning();
           }
       });
      
   }
  
   public void setPort(){
       portNum=Integer.parseInt(port.getText());
   }
  
   public void startRunning(){
       try{
           server=new ServerSocket(portNum,100);
           while(true){
               try{
                   waitForConnection();
                   setupStreams();
                   whileChatting();
                  
               }catch(EOFException eofException){
                   showMessage("\n Server ended the connection");
               }
               finally{
                   closeAll();
               }
           }
       }catch(IOException ioException){
           ioException.printStackTrace();
       }
   }
  
   private void waitForConnection() throws IOException{
       showMessage("\n Waiting for someone to connect...");
       connection=server.accept();
       showMessage("\n Now connected to "+connection.getInetAddress().getHostName());

   }
  
   private void setupStreams() throws IOException{
       output = new ObjectOutputStream(connection.getOutputStream()); 
       output.flush();
       input= new ObjectInputStream(connection.getInputStream());
       showMessage("\n Streams are now set up");
   }
  
   private void whileChatting() throws IOException{
       String message="You are now connected";
       sendMessage(message);
       ableToType(true);
       do{
           try{
               message = (String) input.readObject();
               showMessage("\n"+message);
           }catch(ClassNotFoundException classNotFoundException){
               showMessage("\n I dont know what the user sent");
           }
       }while(!message.equals("CLIENT - END"));
   }
  
   private void closeAll(){
       showMessage("\n Closing connection... \n");
       ableToType(false);
       try{
           output.close();
           input.close();
           connection.close();
       }catch(IOException ioException){
           ioException.printStackTrace();
       }
   }
  
   private void sendMessage(String message){
       try {
           output.writeObject("SERVER - "+message);
           output.flush();
           showMessage("\n SERVER - "+message);
       }catch(IOException ioException) {
           chatWindow.append("\n ERROR: Message not sent");
       }
   }
  
   private void showMessage(final String text){
       SwingUtilities.invokeLater(
           new Runnable(){
               public void run(){
                   chatWindow.append(text);
               }
           }
       );
   }
  
   private void ableToType(final boolean tof){
       SwingUtilities.invokeLater(
           new Runnable(){
               public void run(){
                   userText.setEditable(tof);
               }
           }
       );
   }  
}

ServerTest class:

Java:
import javax.swing.*;
public class ServerTest {
  
  
public static void main(String[] args) {
   Server obj=new Server();
  
}

}
 
Last edited by a moderator:
Joined
Apr 25, 2017
Messages
251
Reaction score
33
You have while(true) in your code,thats why your program goes into infinite loop
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,062
Latest member
OrderKetozenseACV

Latest Threads

Top