【java】网络

来源:互联网 发布:硬盘数据恢复软件排名 编辑:程序博客网 时间:2024/06/06 13:01

     1.引言

       了解IP、TCP、UDP等相关概念,计算机网络相关知识。

      java支持基于流的通信(使用TCP)和基于包的通信(使用UDP)。TCP是可靠的、无损失的,而UDP协议不能保证传输没有丢失。

    2.客户端/服务器计算

    java API提供用于创建套接字的类来便于程序的网络通信。套接字(Socket)是两台主机之间逻辑连接的断点,可以用来发送和接收数据。


client.java

package test;import java.io.*;import java.net.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Client extends JFrame {  // Text field for receiving radius  private JTextField jtf = new JTextField();  // Text area to display contents  private JTextArea jta = new JTextArea();  // IO streams  private DataOutputStream toServer;  private DataInputStream fromServer;  public static void main(String[] args) {    new Client();  }  public Client() {    // Panel p to hold the label and text field    JPanel p = new JPanel();    p.setLayout(new BorderLayout());    p.add(new JLabel("Enter radius"), BorderLayout.WEST);    p.add(jtf, BorderLayout.CENTER);    jtf.setHorizontalAlignment(JTextField.RIGHT);    setLayout(new BorderLayout());    add(p, BorderLayout.NORTH);    add(new JScrollPane(jta), BorderLayout.CENTER);    jtf.addActionListener(new ButtonListener()); // Register listener    setTitle("Client");    setSize(500, 300);    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    setVisible(true); // It is necessary to show the frame here!    try {      // Create a socket to connect to the server      Socket socket = new Socket("localhost", 8000);      // Socket socket = new Socket("130.254.204.36", 8000);      // Socket socket = new Socket("drake.Armstrong.edu", 8000);      // Create an input stream to receive data from the server      fromServer = new DataInputStream(        socket.getInputStream());      // Create an output stream to send data to the server      toServer =        new DataOutputStream(socket.getOutputStream());    }    catch (IOException ex) {      jta.append(ex.toString() + '\n');    }  }  private class ButtonListener implements ActionListener {    public void actionPerformed(ActionEvent e) {      try {        // Get the radius from the text field        double radius = Double.parseDouble(jtf.getText().trim());        // Send the radius to the server        toServer.writeDouble(radius);        toServer.flush();                /*        你说的是flush()函数吧。        flush() 是把缓冲区的数据强行输出,(注意不要和frush()刷新混淆了)        主要用在IO中,即清空缓冲区数据,一般在读写流(stream)的时候,数据是先被读到了内存中,        再把数据写到文件中,当你数据读完的时候不代表你的数据已经写完了,因为还有一部分有可能会留在内存这个缓冲区中。        这时候如果你调用了close()方法关闭了读写流,那么这部分数据就会丢失,所以应该在关闭读写流之前先flush()。*/ /* flush()方法:冲走。意思是把缓冲区的内容强制的写出。        因为操作系统的某些机制,为了防止一直不停地磁盘读写,所以有了延迟写入的概念。        在网络web服务器上也是,为了防止写一个字节就发送一个消息,所以有缓冲区的概念,比如64K的内存区域,        缓冲区写满了再一次性写入磁盘之中(或者发送给客户端浏览器)。   flush方法一般是程序写入完成时执行。随后跟着close方法。例如:// 取得输出流。当然,看具体环境。        PrintWriter out = Util.getWriter();        out.println("输出一些信息,可能很多");        out.flush(); out.close();*/                                        // Get area from the server        double area = fromServer.readDouble();        // Display to the text area        jta.append("Radius is " + radius + "\n");        jta.append("Area received from the server is "          + area + '\n');      }      catch (IOException ex) {        System.err.println(ex);      }    }  }}


server.java


package test;import java.io.*;import java.net.*;import java.util.*;import java.awt.*;import javax.swing.*;public class Server extends JFrame {  // Text area for displaying contents  private JTextArea jta = new JTextArea();  public static void main(String[] args) {    new Server();  }  public Server() {    // Place text area on the frame    setLayout(new BorderLayout());    add(new JScrollPane(jta), BorderLayout.CENTER);    setTitle("Server");    setSize(500, 300);    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    setVisible(true); // It is necessary to show the frame here!    try {      // Create a server socket//    在端口上创建服务器套接字      ServerSocket serverSocket = new ServerSocket(8000);      jta.append("Server started at " + new Date() + '\n');      // Listen for a connection request//      创建连接到客户的套接字      Socket socket = serverSocket.accept();      // Create data input and output streams      DataInputStream inputFromClient = new DataInputStream(        socket.getInputStream());      DataOutputStream outputToClient = new DataOutputStream(        socket.getOutputStream());      while (true) {        // Receive radius from the client        double radius = inputFromClient.readDouble();        // Compute area        double area = radius * radius * Math.PI;        // Send area back to the client        outputToClient.writeDouble(area);        jta.append("Radius received from client: " + radius + '\n');        jta.append("Area found: " + area + '\n');      }    }    catch(IOException ex) {      System.err.println(ex);    }  }}

3.InetAddress类

package test;import java.net.*;public class Server {  public static void main(String[] args) {    for (int i = 0; i < args.length; i++) {      try {        InetAddress address = InetAddress.getByName(args[i]);        System.out.print("Host name: " + address.getHostName() + " ");        System.out.println("IP address: " + address.getHostAddress());      }      catch (UnknownHostException ex) {        System.err.println("Unknown host or IP address " + args[i]);      }    }  }}

4.服务多个客户端


package test;import java.io.*;import java.net.*;import java.util.*;import java.awt.*;import javax.swing.*;public class Server extends JFrame {  // Text area for displaying contents  private JTextArea jta = new JTextArea();  public static void main(String[] args) {    new Server();  }  public Server() {    // Place text area on the frame    setLayout(new BorderLayout());    add(new JScrollPane(jta), BorderLayout.CENTER);    setTitle("Server");    setSize(500, 300);    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    setVisible(true); // It is necessary to show the frame here!    try {      // Create a server socket      ServerSocket serverSocket = new ServerSocket(8000);      jta.append("Server started at " + new Date() + '\n');      // Number a client      int clientNo = 1;      while (true) {        // Listen for a new connection request        Socket socket = serverSocket.accept();        // Display the client number        jta.append("Starting thread for client " + clientNo +          " at " + new Date() + '\n');        //using InetAddress to find the client's host name, and IP address        InetAddress inetAddress = socket.getInetAddress();        jta.append("Client " + clientNo + "'s host name is "          + inetAddress.getHostName() + "\n");        jta.append("Client " + clientNo + "'s IP Address is "          + inetAddress.getHostAddress() + "\n");        // Create a new thread for the connection        HandleAClient task = new HandleAClient(socket);        // Start the new thread        new Thread(task).start();        // Increment clientNo        clientNo++;      }    }    catch(IOException ex) {      System.err.println(ex);    }  }  // Inner class  // Define the thread class for handling new connection  class HandleAClient implements Runnable {    private Socket socket; // A connected socket    /** Construct a thread */    public HandleAClient(Socket socket) {      this.socket = socket;    }    /** Run a thread */    public void run() {      try {                    // Create data input and output streams        DataInputStream inputFromClient = new DataInputStream(          socket.getInputStream());        DataOutputStream outputToClient = new DataOutputStream(          socket.getOutputStream());        //        这个部分的内容是不变的,都是永真,然后从客户端读取数据,完成计算过程再是输出到客户端即可        // Continuously serve the client        while (true) {          // Receive radius from the client          double radius = inputFromClient.readDouble();          // Compute area          double area = radius * radius * Math.PI;          // Send area back to the client          outputToClient.writeDouble(area);          jta.append("radius received from client: " +            radius + '\n');          jta.append("Area found: " + area + '\n');        }      }      catch(IOException e) {        System.err.println(e);      }    }  }}

5.applet客户端

server .java 

package test;import java.io.*;public class Helloworld{ public static void main ( String[] args )  {   String fileName = "intData.dat" ;     long sum = 0;   try   {           DataInputStream instr =        new DataInputStream(         new BufferedInputStream(           new FileInputStream( fileName ) ) );     sum += instr.readInt();     sum += instr.readInt();     sum += instr.readInt();     sum += instr.readInt();          System.out.println( "The sum is: " + sum );     instr.close();   }   catch ( IOException iox )   {     System.out.println("Problem reading " + fileName );   } }}

client.java

package test;import java.io.*;import java.net.*;import javax.swing.*;public class Client extends JApplet {  // Label for displaying the visit count  private JLabel jlblCount = new JLabel();  // Indicate if it runs as application  private boolean isStandAlone = false;  // Host name or ip  private String host = "localhost";  /** Initialize the applet */  public void init() {    add(jlblCount);    try {      // Create a socket to connect to the server      Socket socket;      if (isStandAlone)        socket = new Socket(host, 8000);      else//      当它作为applet运行时,它使用getCodeBase().getHost()方法来返回服务器的IP地址//      getCodeBase:the base URL of the directory which contains this applet.//      getHost():Returns the host name component of the URL.        socket = new Socket(getCodeBase().getHost(), 8000);      // Create an input stream to receive data from the server      DataInputStream inputFromServer =        new DataInputStream(socket.getInputStream());      // Receive the count from the server and display it on label      int count = inputFromServer.readInt();      jlblCount.setText("You are visitor number " + count);      // Close the stream      inputFromServer.close();    }    catch (IOException ex) {      ex.printStackTrace();    }  }  /** Run the applet as an application */  public static void main(String[] args) {    // Create a frame    JFrame frame = new JFrame("Applet Client");    // Create an instance of the applet    Client applet = new Client();    applet.isStandAlone = true;    // Get host//  当它作为引用程序运行时,它传递来自命令行的URL    /*java程序有一个主方法,是这样的public static void main(String [] args)    你说的args[0]就是你用命令行编译运行java程序时,传入的第一个参数*/    if (args.length == 1) applet.host = args[0];    // Add the applet instance to the frame    frame.add(applet, java.awt.BorderLayout.CENTER);    // Invoke init() and start()    applet.init();    applet.start();    // Display the frame    frame.pack();    frame.setVisible(true);  }}


6.发送和接受对象


package test;public class StudentAddress implements java.io.Serializable {  private String name;  private String street;  private String city;  private String state;  private String zip;  public StudentAddress(String name, String street, String city,    String state, String zip) {    this.name = name;    this.street = street;    this.city = city;    this.state = state;    this.zip = zip;  }  public String getName() {    return name;  }  public String getStreet() {    return street;  }  public String getCity() {    return city;  }  public String getState() {    return state;  }  public String getZip() {    return zip;  }}

package test;import java.io.*;import java.net.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;public class Studentclient extends JApplet {  private JTextField jtfName = new JTextField(32);  private JTextField jtfStreet = new JTextField(32);  private JTextField jtfCity = new JTextField(20);  private JTextField jtfState = new JTextField(2);  private JTextField jtfZip = new JTextField(5);  // Button for sending a student to the server  private JButton jbtRegister = new JButton("Register to the Server");  // Indicate if it runs as application  private boolean isStandAlone = false;  // Host name or ip  String host = "localhost";  public void init() {    // Panel p1 for holding labels Name, Street, and City    JPanel p1 = new JPanel();    p1.setLayout(new GridLayout(3, 1));    p1.add(new JLabel("Name"));    p1.add(new JLabel("Street"));    p1.add(new JLabel("City"));    // Panel jpState for holding state    JPanel jpState = new JPanel();    jpState.setLayout(new BorderLayout());    jpState.add(new JLabel("State"), BorderLayout.WEST);    jpState.add(jtfState, BorderLayout.CENTER);    // Panel jpZip for holding zip    JPanel jpZip = new JPanel();    jpZip.setLayout(new BorderLayout());    jpZip.add(new JLabel("Zip"), BorderLayout.WEST);    jpZip.add(jtfZip, BorderLayout.CENTER);    // Panel p2 for holding jpState and jpZip    JPanel p2 = new JPanel();    p2.setLayout(new BorderLayout());    p2.add(jpState, BorderLayout.WEST);    p2.add(jpZip, BorderLayout.CENTER);    // Panel p3 for holding jtfCity and p2    JPanel p3 = new JPanel();    p3.setLayout(new BorderLayout());    p3.add(jtfCity, BorderLayout.CENTER);    p3.add(p2, BorderLayout.EAST);    // Panel p4 for holding jtfName, jtfStreet, and p3    JPanel p4 = new JPanel();    p4.setLayout(new GridLayout(3, 1));    p4.add(jtfName);    p4.add(jtfStreet);    p4.add(p3);    // Place p1 and p4 into StudentPanel    JPanel studentPanel = new JPanel(new BorderLayout());    studentPanel.setBorder(new BevelBorder(BevelBorder.RAISED));    studentPanel.add(p1, BorderLayout.WEST);    studentPanel.add(p4, BorderLayout.CENTER);    // Add the student panel and button to the applet    add(studentPanel, BorderLayout.CENTER);    add(jbtRegister, BorderLayout.SOUTH);    // Register listener    jbtRegister.addActionListener(new ButtonListener());    // Find the IP address of the Web server    if (!isStandAlone)      host = getCodeBase().getHost();  }  /** Handle button action */  private class ButtonListener implements ActionListener {    public void actionPerformed(ActionEvent e) {      try {        // Establish connection with the server        Socket socket = new Socket(host, 8000);        // Create an output stream to the server        ObjectOutputStream toServer =          new ObjectOutputStream(socket.getOutputStream());        // Get text field        String name = jtfName.getText().trim();        String street = jtfStreet.getText().trim();        String city = jtfCity.getText().trim();        String state = jtfState.getText().trim();        String zip = jtfZip.getText().trim();        // Create a Student object and send to the server        StudentAddress s =          new StudentAddress(name, street, city, state, zip);        toServer.writeObject(s);      }      catch (IOException ex) {        System.err.println(ex);      }    }  }  /** Run the applet as an application */  public static void main(String[] args) {    // Create a frame    JFrame frame = new JFrame("Register Student Client");    // Create an instance of the applet    Studentclient applet = new Studentclient();    applet.isStandAlone = true;    // Get host    if (args.length == 1) applet.host = args[0];    // Add the applet instance to the frame    frame.add(applet, BorderLayout.CENTER);    // Invoke init() and start()    applet.init();    applet.start();    // Display the frame    frame.pack();    frame.setVisible(true);  }}

package test;import java.io.*;import java.net.*;public class StudentServer {  private ObjectOutputStream outputToFile;  private ObjectInputStream inputFromClient;  public static void main(String[] args) {    new StudentServer();  }  public StudentServer() {    try {      // Create a server socket      ServerSocket serverSocket = new ServerSocket(8000);      System.out.println("Server started ");      // Create an object ouput stream      outputToFile = new ObjectOutputStream(        new FileOutputStream("student.dat", true));      while (true) {        // Listen for a new connection request        Socket socket = serverSocket.accept();        // Create an input stream from the socket        inputFromClient =          new ObjectInputStream(socket.getInputStream());        // Read from input        Object object = inputFromClient.readObject();        // Write to the file        outputToFile.writeObject(object);        System.out.println("A new student object is stored");      }    }    catch(ClassNotFoundException ex) {      ex.printStackTrace();    }    catch(IOException ex) {      ex.printStackTrace();    }    finally {      try {        inputFromClient.close();        outputToFile.close();      }      catch (Exception ex) {        ex.printStackTrace();      }    }  }}


7.从web服务器上读取文件


package test;import java.awt.*;import java.awt.event.*;import java.io.*;import java.net.*;import javax.swing.*;public class ViewRemoteFile extends JApplet {  // Button to view the file  private JButton jbtView = new JButton("View");  // Text field to receive file name  private JTextField jtfURL = new JTextField(12);  // Text area to store file  private JTextArea jtaFile = new JTextArea();  // Label to display status  private JLabel jlblStatus = new JLabel();  /** Initialize the applet */  public void init() {    // Create a panel to hold a label, a text field, and a button    JPanel p1 = new JPanel();    p1.setLayout(new BorderLayout());    p1.add(new JLabel("Filename"), BorderLayout.WEST);    p1.add(jtfURL, BorderLayout.CENTER);    p1.add(jbtView, BorderLayout.EAST);    // Place text area and panel p to the applet    setLayout(new BorderLayout());    add(new JScrollPane(jtaFile), BorderLayout.CENTER);    add(p1, BorderLayout.NORTH);    add(jlblStatus, BorderLayout.SOUTH);    // Register listener to handle the "View" button    jbtView.addActionListener(new ActionListener() {      public void actionPerformed(ActionEvent e) {        showFile();      }    });  }  private void showFile() {java.util.Scanner input = null; // Use Scanner for getting text input    URL url = null;    try {      // Obtain URL from the text field      url = new URL(jtfURL.getText().trim());      // Create a Scanner for input stream      input = new java.util.Scanner(url.openStream());      // Read a line and append the line to the text area      while (input.hasNext()) {        jtaFile.append(input.nextLine() + "\n");      }      jlblStatus.setText("File loaded successfully");    }    catch (MalformedURLException ex) {  jlblStatus.setText("URL " + url + " not found.");    }    catch (IOException e) {      jlblStatus.setText(e.getMessage());    }    finally {      if (input != null) input.close();    }  }  /** Main method */  public static void main(String[] args) {    // Create a frame    JFrame frame = new JFrame("View File From a Web Server");    // Create an instance of ViewRemoteFile    ViewRemoteFile applet = new ViewRemoteFile();    // Add the applet instance to the frame    frame.add(applet, BorderLayout.CENTER);    // Invoke init() and start()    applet.init();    applet.start();    // Display the frame    frame.setSize(300, 300);    frame.setVisible(true);  }}

0 0
原创粉丝点击