Java Client/Server Socket Example

  • Server
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
 
import java.io.*;
import java.net.*;
 
class SocketServer extends JFrame
		implements ActionListener {
 
   JButton button;
   JLabel label = new JLabel("Text received over socket:");
   JPanel panel;
   JTextArea textArea = new JTextArea();
   ServerSocket server = null;
   Socket client = null;
   BufferedReader in = null;
   PrintWriter out = null;
   String line;
 
   SocketServer(){ //Begin Constructor
     button = new JButton("Click Me");
     button.addActionListener(this);
 
     panel = new JPanel();
     panel.setLayout(new BorderLayout());
     panel.setBackground(Color.white);
     getContentPane().add(panel);
     panel.add("North", label);
     panel.add("Center", textArea);
     panel.add("South", button);
 
   } //End Constructor
 
  public void actionPerformed(ActionEvent event) {
     Object source = event.getSource();
 
     if(source == button){
         textArea.setText(line);
     }
  }
 
  public void listenSocket(){
 
    try{
      server = new ServerSocket(4444); 
    } catch (IOException e) {
      System.out.println("Could not listen on port 4444");
      System.exit(-1);
    }
 
    try{
      client = server.accept();
    } catch (IOException e) {
      System.out.println("Accept failed: 4444");
      System.exit(-1);
    }
 
    try{
      in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      out = new PrintWriter(client.getOutputStream(), true);
    } catch (IOException e) {
      System.out.println("Accept failed: 4444");
      System.exit(-1);
    }
 
    while(true){
      try{
        line = in.readLine();
        //Send data back to client
        out.println(line);
      } catch (IOException e) {
        System.out.println("Read failed");
        System.exit(-1);
      }
    }
  }
 
  protected void finalize(){
//Clean up 
     try{
        in.close();
        out.close();
        server.close();
    } catch (IOException e) {
        System.out.println("Could not close.");
        System.exit(-1);
    }
  }
 
  public static void main(String[] args){
        SocketServer frame = new SocketServer();
        frame.setTitle("Server Program");
        WindowListener l = new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                        System.exit(0);
                }
        };
        frame.addWindowListener(l);
        frame.pack();
        frame.setVisible(true);
	frame.listenSocket();
  }
}
  • Client
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
 
import java.io.*;
import java.net.*;
 
class SocketClient extends JFrame
		 implements ActionListener {
 
   JLabel text, clicked;
   JButton button;
   JPanel panel;
   JTextField textField;
   Socket socket = null;
   PrintWriter out = null;
   BufferedReader in = null;
 
   SocketClient(){ //Begin Constructor
     text = new JLabel("Text to send over socket:");
     textField = new JTextField(20);
     button = new JButton("Click Me");
     button.addActionListener(this);
 
     panel = new JPanel();
     panel.setLayout(new BorderLayout());
     panel.setBackground(Color.white);
     getContentPane().add(panel);
     panel.add("North", text);
     panel.add("Center", textField);
     panel.add("South", button);
   } //End Constructor
 
  public void actionPerformed(ActionEvent event){
     Object source = event.getSource();
 
     if(source == button){
//Send data over socket
          String text = textField.getText();
          out.println(text);
	  textField.setText(new String(""));
//Receive text from server
       try{
	  String line = in.readLine();
          System.out.println("Text received :" + line);
       } catch (IOException e){
	 System.out.println("Read failed");
       	 System.exit(1);
       }
     }
  }
 
  public void listenSocket(){
//Create socket connection
     try{
       socket = new Socket("localhost", 4444);
       out = new PrintWriter(socket.getOutputStream(), true);
       in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     } catch (UnknownHostException e) {
       System.out.println("Unknown host: kq6py.eng");
       System.exit(1);
     } catch  (IOException e) {
       System.out.println("No I/O");
       System.exit(1);
     }
  }
 
   public static void main(String[] args){
        SocketClient frame = new SocketClient();
        frame.setTitle("Client Program");
        WindowListener l = new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                        System.exit(0);
                }
        };
 
        frame.addWindowListener(l);
        frame.pack();
        frame.setVisible(true);
	frame.listenSocket();
  }
}

javaclientsocket.txt · Last modified: 2014/10/26 01:52 (external edit)
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0