Java Network Programming (ii) client and server side (TCP) __ Programming

Source: Internet
Author: User

TCP-oriented protocols are more secure, similar to phone calls, but less efficient. Its basic model is request-respond. In here we use the things Java has encapsulated socket class ServerSocket and sockets
The former is the server, the latter is the client, this has a little different, the client's port is automatic acquisition do not need us like UDP also need us to specify, when the C, s to establish a connection between the two to establish a pipeline, the server output stream is the client's input stream.

For communication between the client and the server. The client is receiving data + sending data
1. Client:

public class Clients {public
    static void Main (string[] args) throws Unknownhostexception, IOException {
        //TODO A uto-generated method Stub
        Socket client=new socket ("localhost", 5888);
        Char[] Cbuf=new char[1024];
        InputStreamReader in=new InputStreamReader (Client.getinputstream ());
        In.read (CBUF);
        System.out.println (string.valueof (CBUF));





    }


2. Service-Side communication:

public class Servers {public static void main (String [] arg) throws ioexception{
        Versocket server=new ServerSocket (5888);
        Socket socket=server.accept ();
        SYSTEM.OUT.PRINTLN ("Success");
        BufferedWriter bf=new BufferedWriter (New OutputStreamWriter (Socket.getoutputstream ()));
        Bf.write ("Wangjun");



    Bf.flush (); }

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.