TCP/IP Client程式

來源:cww

 

主要是java.net.Socket 物件的應用,其Constructor主要是

      Socket(String ip, int PortNo)

      Socket(InetAddress Address, int PortNo)

InetAddress物件有幾個有用的(static) Method

static InetAddress getLocalHost() throws UnknownHostException

static InetAddress getByName(String hostName) throws UnknownHostException

String getHostAddress()   eg. 192.168.0.152

String getHostName()      eg. cwweis98

 

Socket Client端的程比式比較簡單,相對的說明請見TCP/IP Server程式

 

    try {

        //設定Socket連線

        Socket s=new Socket("192.168.0.152",5051);

        //設定傳送接收DataTimeOut的毫秒數

        s.setSoTimeout(5000);

        in = new BufferedReader(new InputStreamReader(

                   s.getInputStream()));

        out = new PrintWriter(s.getOutputStream(),true);

 

    } catch (UnknownHostException se) {

    }

------------------------------frame1.java -------------------------------------------

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.net.*;

import java.io.*;

import java.util.*;

 

 

public class Frame1 extends JFrame {

  PrintWriter out = null;

  BufferedReader in = null;

  Socket s;

 

  JPanel contentPane;

  JButton jButton1 = new JButton();

  JTextField jTextField1 = new JTextField();

  JButton jButton2 = new JButton();

  JScrollPane jScrollPane1 = new JScrollPane();

  JTextArea jTextArea1 = new JTextArea();

 

  /**Construct the frame*/

  public Frame1() {

    enableEvents(AWTEvent.WINDOW_EVENT_MASK);

    try {

      jbInit();

    }

    catch(Exception e) {

      e.printStackTrace();

    }

  }

  /**Component initialization*/

  private void jbInit() throws Exception  {

    jButton1.setText("Send");

    jButton1.setBounds(new Rectangle(54, 59, 137, 24));

    jButton1.addActionListener(new java.awt.event.ActionListener() {

      public void actionPerformed(ActionEvent e) {

        jButton1_actionPerformed(e);

      }

    });

    //setIconImage(Toolkit.getDefaultToolkit().createImage(Frame1.class.getResource("[Your Icon]")));

    contentPane = (JPanel) this.getContentPane();

    contentPane.setLayout(null);

    this.setSize(new Dimension(400, 300));

    this.setTitle("Frame Title");

    jTextField1.setText("jTextField1");

    jTextField1.setBounds(new Rectangle(59, 29, 263, 21));

    jButton2.setText("Close");

    jButton2.setBounds(new Rectangle(211, 59, 106, 26));

    jButton2.addActionListener(new java.awt.event.ActionListener() {

      public void actionPerformed(ActionEvent e) {

        jButton2_actionPerformed(e);

      }

    });

 

    jScrollPane1.setBounds(new Rectangle(45, 95, 283, 117));

    jTextArea1.setText("jTextArea1");

    contentPane.add(jTextField1, null);

    contentPane.add(jButton1, null);

    contentPane.add(jButton2, null);

    contentPane.add(jScrollPane1, null);

    jScrollPane1.getViewport().add(jTextArea1, null);

    try {

        //設定Socket連線

        Socket s=new Socket("192.168.0.152",5051);

        //設定傳送接收DataTimeOut的毫秒數

        s.setSoTimeout(5000);

        in = new BufferedReader(new InputStreamReader(

                   s.getInputStream()));

        out = new PrintWriter(s.getOutputStream(),true);

 

    } catch (UnknownHostException se) {

      jTextArea1.setText( "UnKnowHost!!" + "\n" );

    } catch (IOException se) {

      jTextArea1.setText( "Init IO Error!! \n" );

    }

 

 

  }

  /**Overridden so we can exit when window is closed*/

  protected void processWindowEvent(WindowEvent e) {

 

    if (e.getID() == WindowEvent.WINDOW_CLOSING) {

 

      super.processWindowEvent(e);

      System.exit(0);

    }

  }

 

  void jButton1_actionPerformed(ActionEvent e) {

       try {

         //送出一行DataServer後,立即等待接收回應

         out.println(jTextField1.getText());

         jTextArea1.setText(jTextArea1.getText()+ in.readLine() + "\n");

       } catch (IOException se) {

         jTextArea1.setText(jTextArea1.getText()+  "IO Error \n");

       }

  }

 

  void jButton2_actionPerformed(ActionEvent e) {

       try {

          out.println("Close");

          in.close();

          out.close();

          s.close();

       } catch (IOException se) {

          jTextArea1.setText(jTextArea1.getText()+  "IO Error \n");

       } catch (Exception se) {

          jTextArea1.setText(jTextArea1.getText()+ se.getMessage() + "\n");

       }

  }

 

 

}

----------------------------------------Application1.java -----------------------------------

import javax.swing.UIManager;

import java.awt.*;

 

public class Application1 {

  boolean packFrame = false;

 

  /**Construct the application*/

  public Application1() {

    Frame1 frame = new Frame1();

    //Validate frames that have preset sizes

    //Pack frames that have useful preferred size info, e.g. from their layout

    if (packFrame) {

      frame.pack();

    }

    else {

      frame.validate();

    }

    //Center the window

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

    Dimension frameSize = frame.getSize();

    if (frameSize.height > screenSize.height) {

      frameSize.height = screenSize.height;

    }

    if (frameSize.width > screenSize.width) {

      frameSize.width = screenSize.width;

    }

    frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);

    frame.setVisible(true);

  }

  /**Main method*/

  public static void main(String[] args) {

    try {

      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

    }

    catch(Exception e) {

      e.printStackTrace();

    }

    new Application1();

  }

}