Java Network programming

Source: Internet
Author: User
Tags readline

Network Programming Overview
    • Network programming: To realize the sharing of data between different computers by programming
    • C/S: Client/server Mode
      1. Benefit: Some of the code is placed on the client and the access server only needs to transfer valid data.
      2. Cons: The client must be installed and the server upgraded, and the corresponding client must be upgraded.
    • b/S: Browser/server Mode
      1. Benefit: You do not need to install the client, you do not need to consider server upgrade issues.
      2. Cons: All data is in the server, the network is not good, slow response, unfriendly.
Three elements of network programming
    1. Protocol: Rules for transmission between computers and computers (three elements of the agreement are as follows)
      1. Grammar, that is, this section of content to conform to certain rules and formats. For example, parentheses are paired, ending with semicolons, and so on.
      2. Semantics, is that this section of content to represent a certain meaning. For example, a number minus a number is meaningful, and a number minus text is generally meaningless.
      3. The order is what to do first and what to do after. For example, you can add a value first, and then subtract a value.
    2. IP address: In the network, the IP address is uniquely identified
    3. Port number: Unique identifier of the application in the computer
Code steps for the client
    1. Create the Socket object, specify the IP address and port number
    2. Get a file byte output stream object using the socket (you can use a transform stream to flow bytes into a print stream)
    3. Sending messages using byte flow to the server
    4. Close the socket resource
Code steps for the service side
    1. Create a ServerSocket object, set the port number
    2. Use the Sccept method to get the socket object using the created ServerSocket object
    3. Use the socket acquired by the second step to get the byte input stream object (you can stream bytes to character flow only with the transform stream)
    4. Read the information sent by the client using the third step stream
    5. Close Resource

Throughout the process, it is important to remember to flush the buffer and close the stream at any time, so it is recommended to use a print stream, which automatically refreshes and wraps automatically.

Write a small example to achieve a single communication between the client and the server

Package Homework.demo5;import Java.io.*;import java.net.socket;/** * Create client * * @author wzlove * @create 2018-07-25 20:47 * /public class Clientdemo {public static void main (string[] args) throws IOException {//Create socket Object Sock        ET socket = new socket ("localhost", 8888);        Convert the conversion flow into a print stream printwriter pw = new PrintWriter (New OutputStreamWriter (Socket.getoutputstream ()), true);        Write content to the server pw.println ("Hello, I am the client");        Gets the efficient character input stream BufferedReader br = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));        Gets the message sent by the server String s = br.readline ();        SYSTEM.OUT.PRINTLN ("server says:" + s);    Close flow socket.close (); }}package homework.demo5;import java.io.*;import java.net.serversocket;import java.net.socket;/** * Service side * * @author  Wzlove * @create 2018-07-25 20:57 */public class Serverdemo {public static void main (string[] args) throws IOException {//Create server-Side network object, specify port number ServerSocket SS = new SeRversocket (8888);        Get socket Object Socket accept = Ss.accept ();        Get an efficient input stream bufferedreader br = new BufferedReader (New InputStreamReader (Accept.getinputstream ()));        Gets the input information of String s = br.readline ();        SYSTEM.OUT.PRINTLN ("client says:" + s);        Gets the print stream printwriter pw = new PrintWriter (New OutputStreamWriter (Accept.getoutputstream ()), true);        Send a message to the client pw.println ("Hello, I am the server");        Close resource Accept.close ();    Ss.close (); }}

Write an example to enable the client to upload pictures to the server

Package Homework.demo7;import Java.io.*;import java.net.socket;/** * Client in network communication */public class Cilent {public static VO        ID Main (string[] args) throws IOException {//Create socket client Object Socket SOCKET = new socket ("localhost", 8888);        Prepare the file for transmission Bufferedinputstream bis = new Bufferedinputstream (New FileInputStream ("yz.jpg"));        Use the socket object to get the byte input stream object Bufferedoutputstream bos = new Bufferedoutputstream (Socket.getoutputstream ());        While reading a file, sending data to the server byte[] arr = new byte[1024 * 5];        int Len;        while (len = Bis.read (arr))! =-1) {bos.write (Arr,0,len);        }//Data upload completed, refresh buffer Bos.flush ();        Close unused resources bis.close ();        Turn off the output stream socket, this step is required socket.shutdownoutput (); Read feedback data//Use socket object to get byte input stream bufferedreader br = new BufferedReader (New InputStreamReader (socket.getinput        Stream ()));        String Line;        StringBuilder sb = new StringBuilder (); while (LiNE = br.readline ()) = null) {sb.append (line);        } System.out.println (SB);    Close resource Socket.close (); }}package homework.demo7;import java.io.*;import java.net.serversocket;import java.net.socket;/** * Server */public class Server {public static void main (string[] args) throws IOException {//Create service-side object ServerSocket SS = new Se        Rversocket (8888);        Get the socket object using the server-side object Socket accept = Ss.accept (); Prepare to accept the uploaded file and write to the server//create an efficient byte output stream to point to the file bufferedoutputstream bos = new Bufferedoutputstream (New FILEOUTPUTST        Ream ("test.jpg"));        Use the socket object to get the file byte input stream (into the efficient byte input stream) Bufferedinputstream bis = new Bufferedinputstream (Accept.getinputstream ());        Read side write byte[] arr = new byte[1024 * 5];        int Len;            while (len = Bis.read (arr))! =-1) {bos.write (Arr,0,len);        To refresh the Bos.flush ();        }//Close unused resources bos.close (); Feedback information to the client PRintwriter pw = new PrintWriter (New OutputStreamWriter (Accept.getoutputstream ()), true);        Write Information pw.println ("Upload success");        Close resource Accept.close ();    Ss.close (); }}

Relevant knowledge of the network you can subscribe to the amusing network protocol on the Geek's time, that's very clear.

Java Network programming

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.