Introduction to Java Socket (socket) network programming _java

Source: Internet
Author: User
Tags gettext

The main network application modes are:

    • Host/terminal mode: Centralized computing, centralized management;
    • Client/server (Client/server, c/s) mode: distributed computing, distribution management;
    • Browser/server Mode: Leverage the Internet across platforms.

The WWW (World Wide Web) is built on client/server mode, based on HTML language and HTTP protocol, and can provide information browsing system for various internet services. The network information is placed in different locations of the host, and the WWW server uses hypertext link to link various information. The WWW client (browser brower) is responsible for establishing contacts with the server, sending requests to the server, processing HTML hypermedia, providing a graphical user interface (GUI), displaying information, and so on.

In client/server mode, on the server side, prepare to accept communication from multiple client computers. To do this, in addition to identifying computers on the Internet with IP addresses, a port number is introduced, with a port number identifying the thread that is running the server-side background service. The combination of a port number and an IP address is called a network socket (socket).

Java language in the implementation of C/s mode, sockets are divided into two categories:

    1. On the server side, the ServerSocket class supports the underlying network traffic;
    2. On the client side, the socket class supports the underlying communication of the network.

The server machine provides client-oriented services through the port (bus I/O address), and the server machine provides several different services at the same time on several different ports. The client accesses a port at one end of the server that is brought to the server for service. Provisions: Port number 0~1023 for system-specific. For example, the HTTP protocol is in Port 80,telnet protocol on port 23. Port 1024~65535 for application use.

When the client program and the server program need to communicate, you can use the socket class to establish a socket connection. A socket connection can be imagined as a telephone call: The client program initially establishes the call, the server program listens, and after the call completes, either party can speak at any time.

The two sides realize the communication has streaming socket and datagram socket two kinds of optional ways:

    1. A streaming socket is a connected communication, that is, TCP (Transmission Control Protocol): A connection is established before each communication, and the connection is disconnected after the communication has ended. The characteristic is that it can guarantee the correctness and reliability of transmission.
    2. A datagram socket is a connectionless communication, that is, UDP (User Datagram Protocol): The data to be transmitted into small packets, sent directly to the Internet. No need to establish a connection and remove the connection, fast, but no reliable guarantee.

Streaming sockets establish a communication channel between the client program and the server program. Each socket can read and write two operations. For either end, the communication session process with the other party is:
Establish socket connection, get input/output stream, read data/write data, close socket after communication completes (remove connection).

With the socket construction method, you can establish a socket object to the server on the client:
Socket (String host,int Port): Host is the IP address of the server, port is the port number, these are predefined.
For example, code:

  try{
    Socket mysocket = new socket ("Http://www.weixueyuan.net", 1860);
  } catch (IOException e) {}


Then, using the getInputStream () method to obtain the input stream, use this input stream to read the server into the "line" information, use the Getoutputstream () method to obtain the output stream, use this output stream to write the information to "line".

Using the ServerSocket construction method, you can establish a server socket object that accepts client sockets on the server:
ServerSocket (int port): Specifies the port number to create a ServerSocket object. Port number port must be the same as the port number that the customer calls. To do this, use the following form code:

  try{
    ServerSocket serversocket = new ServerSocket (1860);
  catch (IOException e) {}


The server-side program listens on the specified port and, when receiving a service request from the client program, creates a socket object that communicates with the client program for that port. For example, executing the above code to establish a server socket object, after establishing an object ServerSocket, it is possible that it uses the Accept () method to get the socket object and receive information from the socket Mysocket from the client program. As shown in the following code:

  try{
    Socket sc = serversocket.accept ();//ac is a Socket object
  }catch (IOException e) {}


To undo a service, you can close the socket object SC:

  Sc.close ();

"Example" client-side applications in C/S mode. This is a simple example of a client-side streaming socket communication, and the code illustrates how the client-side program is written. In the example, the client program requests port 4441 on the server host and completes the read/write to the server after it is established.

Import java.io.*;
Import java.net.*;
public class client{public
  static void main (string args[]) {
    string s = null; Socket Mysocket;
    DataInputStream in = Null;dataoutputstream out = null;
    try{
      mysocket = new Socket ("localhost", 4441);
      in = new DataInputStream (Mysocket.getinputstream ());
      out = new DataOutputStream (Mysocket.getoutputstream ());
      Out.writeutf ("Good server!");
      while (true) {
        s = In.readutf ();
        if (s==null) break;
        else System.out.println (s);
      }
      Mysocket.close ();
    } catch (IOException e) {
      System.out.println ("can ' t connect");}}

"Example" server-side applications that correspond to client-side applications. Program in 4441-port monitoring, when a client request is detected, generate a "customer, hello, I am the server" string output to the client.

Import Java.io.*;import java.net.*;
public class server{public
  static void Main (String args[]) {
    ServerSocket Server = null;
    Socket you = null; String s = null;
    DataOutputStream out = null;
    DataInputStream in = null;
    try{
      Server = new ServerSocket (4441);
    } catch (IOException E1) {
      System.out.println ("ERROR:" +e1);
    }
    try{You
      = Server.accept ();
      in = new DataInputStream (You.getinputstream ());
      out = new DataOutputStream (for You Getoutputstream ());
      while (true) {
        s = In.readutf ();
        if (s!=null) break;
      Out.writeutf ("Customer, Hello, I am Server");
      Out.close ();
    }
    catch (IOException e) {System.out.println ("ERROR: +e);}}}"

In order to give full play to the parallel work of the computer, you can connect the socket work to a thread to complete. When the client wants to request a service from the server, or when the server receives a service request from a client, it initiates a thread that completes the information communication, creates the input output stream in the thread, and completes the information exchange between the client and the server side.

The

Example places the socket connection work in the thread's client applet. The interface has a Send Message button, a text box, and a text area. The client application first establishes a socket connection with the server. Use the data input stream in the repeatedly read the server into the line of information, will receive the information in the text area display. 婐 the information for the log is "end," closes the socket connection and ends the program. Users can also enter information in a text box and press the Send Message button, and the client program sends the contents of the text box to the server using the data output stream.

Import java.net.*;
Import java.io.*;
Import java.awt.*;
Import javax.swing.*;
Import java.awt.event.*;
Import java.applet.*; public class Aclient extends Applet implements runnable,actionlistener{JButton button; JTextField TEXTF;
  JTextArea texta; Socket socket;
  Thread thread; DataInputStream in;
  DataOutputStream out;
    public void init () {SetBackground (new Color (120,153,137));
    SetLayout (New BorderLayout ());
    button = new JButton ("Send Message");
    TEXTF = new JTextField (20);
    Texta = new JTextArea (20,30);
    SetSize (450,350);
    JPanel p = new JPanel (); P.add (TEXTF);
    P.add (button); Add (texta, "Center");
    Add (P, "South");
  Button.addactionlistener (this);
      public void Start () {try{socket = new Socket (This.getcodebase (). GetHost (), 4441);
      in = new DataInputStream (Socket.getinputstream ());
    out = new DataOutputStream (Socket.getoutputstream ());
      }catch (IOException e) {} if (thread==null) {thread = new thread (this); Thread.sEtpriority (thread.min_priority);
    Thread.Start ();
    The public void Run () {String s = null;
      while (true) {try{s = In.readutf ();
        }catch (IOException e) {} if (S.equals ("End")) {try{socket.close ();
    }catch (IOException e) {}}else Texa.append (s + "\ n");
      } public void actionperformed (ActionEvent e) {if (E.getsource () ==button) {String s = textf.gettext ();
        if (s! = null) {try{OUT.WRITEUTF (s);
        }catch (IOException E1) {}} else{try{Out.writeutf ("Please speak");
 The catch (IOException E1) {}}}}

The

Example program establishes a socket connection to the client with end 4441, and when the server receives a request from the client, it creates a thread with the customer's socket and starts. If there is no client application, continue to monitor the client's application. The thread builds the input data stream in and out of the data stream according to the customer's socket. The thread uses in to read information from the customer into the line. If the accepted information is "end", the server closes the socket connection when it replies "End", otherwise reply: "I am the server you said to me", and the server received the information.

Import java.net.*;
Import java.io.*;
Import java.awt.*;
Import javax.swing.*;
Import java.awt.event.*;
Import java.applet.*; public class Aclient extends Applet implements runnable,actionlistener{JButton button; JTextField TEXTF;
  JTextArea texta; Socket socket;
  Thread thread; DataInputStream in;
  DataOutputStream out;
    public void init () {SetBackground (new Color (120,153,137));
    SetLayout (New BorderLayout ());
    button = new JButton ("Send Message");
    TEXTF = new JTextField (20);
    Texta = new JTextArea (20,30);
    SetSize (450,350);
    JPanel p = new JPanel (); P.add (TEXTF);
    P.add (button); Add (texta, "Center");
    Add (P, "South");
  Button.addactionlistener (this);
      public void Start () {try{socket = new Socket (This.getcodebase (). GetHost (), 4441);
      in = new DataInputStream (Socket.getinputstream ());
    out = new DataOutputStream (Socket.getoutputstream ());
      }catch (IOException e) {} if (thread==null) {thread = new thread (this); Thread.sEtpriority (thread.min_priority);
    Thread.Start ();
    The public void Run () {String s = null;
      while (true) {try{s = In.readutf ();
        }catch (IOException e) {} if (S.equals ("End")) {try{socket.close ();
    }catch (IOException e) {}}else Texa.append (s + "\ n");
      } public void actionperformed (ActionEvent e) {if (E.getsource () ==button) {String s = textf.gettext ();
        if (s! = null) {try{OUT.WRITEUTF (s);
        }catch (IOException E1) {}} else{try{Out.writeutf ("Please speak"); }catch (IOException E1)}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.