Java Learning (VI): Socket Programming Example

Source: Internet
Author: User

The socket is also called a socket, and the application usually makes a request to the network through a "socket" or answers a network request.

Java has simplified the programming interface for sockets. Java provides serversocket to support it. In fact, when creating an instance object of the class and providing a port resource, a fixed location can be set up for other computers to access, such as: ServerSocket server=new serversocket (6789);
A little note here is that the allocation of the port must be unique. Because the port is to uniquely identify each computer's unique service. In addition, the port number is from 0 to 65535, the first 1024 ports have been TCP/IP as a reserved port, so you can only allocate ports after 1024.

 Public classJavatest { Public Static voidMain (string[] args)throwsIOException {//define a ServerSocket listener on port 2222ServerSocket Server =NewServerSocket (2222); //server attempts to receive connection requests from other sockets, the server's accept method is blockedSocket client =server.accept (); BufferedReader in=NewBufferedReader (NewInputStreamReader (Client.getinputstream ())); PrintWriter out=NewPrintWriter (Client.getoutputstream ());  while(true) {String str=In.readline (); Out.println ("has receive the input:" +str);            Out.flush (); if(Str.equals ("End"))            {                 Break;         }} client.close ();    Server.close (); }}

Java Learning (VI): Socket Programming Example

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.