Client Server Coding

(Saturday, June 26, 2010)

My first client server java coding:

   1: import javax.swing.*;
   2: import java.awt.*;
   3: import java.io.*;
   4: import javax.swing.border.*;
   5: import java.net.*;
   6: import java.awt.event.*;
   7:  
   8: class Server extends JFrame implements ActionListener
   9: {
  10:     private JTextArea jtaSend=new JTextArea();
  11:     private JTextArea jtaReceive=new JTextArea();
  12:     private JButton jbtSend=new JButton("Send");
  13:     
  14:     DataOutputStream output;
  15:     DataInputStream input;
  16:     
  17:     public Server()
  18:     {
  19:         jbtSend.addActionListener(this);
  20:     
  21:         try
  22:         {
  23:             ServerSocket server=new ServerSocket(8000);
  24:             Socket socket=server.accept();//wait connection from a client
  25:             System.out.println("connected to a client");
  26:         
  27:             output=new DataOutputStream(socket.getOutputStream());
  28:             input=new DataInputStream(socket.getInputStream());
  29:         
  30:             getContentPane().setLayout(new GridLayout(2,1));
  31:             JScrollPane scp=new JScrollPane(jtaSend);
  32:             scp.setBorder(new TitledBorder("Type your message here"));
  33:         
  34:             JPanel panel=new JPanel();
  35:             panel.setLayout(new BorderLayout());
  36:             panel.add(scp,BorderLayout.CENTER);
  37:             panel.add(jbtSend,BorderLayout.SOUTH);
  38:             getContentPane().add(panel);    
  39:         
  40:             getContentPane().add(new JScrollPane(jtaReceive));
  41:             setTitle("Server");
  42:             setSize(300,300);
  43:         
  44:             setLocation(20,30);
  45:             setVisible(true);
  46:         
  47:             while(true)
  48:             {
  49:                 jtaReceive.setText(input.readUTF());
  50:             }
  51:         }
  52:         catch(IOException ex)
  53:         {
  54:             ex.printStackTrace();
  55:         }
  56:     }
  57:  
  58:     public static void main(String[]args)
  59:     {
  60:         JFrame frame=new Server();
  61:     }
  62:  
  63:     public void actionPerformed(ActionEvent e)
  64:     {
  65:         try
  66:         {
  67:             output.writeUTF(jtaSend.getText());
  68:         }
  69:         catch(Exception ex)
  70:         {
  71:         }
  72:     }
  73: }
Takes in messages from a user and send it to the other. Incomplete code.

Posted by Wai Kit at 10:05 PM

4 comments:

  1. JLean Says:

    Dropping by ere. =).. Do have a peep at mine yeah

  2. Wai Kit Says:

    hey there sure thing :)

  3. Ken Wooi Says:

    oh java, long time no see =P

  4. Wai Kit Says:

    yeah, haha

 
Copyright 2005-2007. Hello Wiki designed by Fen, Blogger Templates by Blogcrowds. Wai Kit Says logo designed by Wai Yen.