Java Network programming

Source: Internet
Author: User

Java Network Programming


Network programming refers to writing programs that run on multiple devices (computers) that are connected through the network.


The J2SE API in the Java.net package contains classes and interfaces that provide low-level communication details. You can use these classes and interfaces directly to focus on solving

Instead of focusing on the details of the communication.


The java.net package provides support for two common network protocols:


TCP:TCP is the abbreviation for Transmission Control Protocol, which guarantees reliable communication between two applications. Usually used for Internet protocols, which are called TCP/IP.


UDP:UDP is an abbreviation for the User Datagram Protocol, a non-connected protocol. A packet that provides the data to be sent between applications.


This tutorial focuses on the following two topics.


Socket Programming: This is the most widely used network concept and it has been explained in very detailed


URL Processing: This section will be in a different space, click here to learn more about URL handling in the Java language.


Socket Programming


Sockets use TCP to provide a mechanism for communication between two computers. The client program creates a socket and tries to connect to the server's socket.


When the connection is established, the server creates a socket object. The client and server can now be made by writing and reading the socket object

Communication.


The Java.net.Socket class represents a socket, and the Java.net.ServerSocket class provides a way for the server program to listen to the client and

The mechanism for establishing a connection.


The following steps occur when a TCP connection is established between two computers using sockets:


The server instantiates a ServerSocket object that communicates through the port on the server.


The server calls the Accept () method of the ServerSocket class, and the method waits until the client connects to the given port on the server.


When the server is waiting, a client instantiates a socket object, specifying the server name and port number to request a connection.


The constructor of the socket class attempts to connect the client to the specified server and port number. If communication is established, a socket object is created on the client

Able to communicate with the server.


On the server side, the Accept () method returns a new socket reference to the server that is connected to the client's socket.


After the connection is established, the communication is made by using the I/O stream. Each socket has an output stream and an input stream. The client's output is connected to the server

The input stream from the client, and the input from the clients to the server-side output stream.


TCP is a two-way communication protocol, so data can be sent over two data streams at the same time. The following are some of the classes provided by a complete set of useful parties

method to achieve sockets.


methods of the ServerSocket class


The server application obtains a port by using the Java.net.ServerSocket class and listens for client requests.


The ServerSocket class has four methods of construction:



Create a non-binding server socket. If the ServerSocket constructor method does not throw an exception, it means that your application has successfully bound to the specified

Port, and listens for client requests.


Here are some common methods for ServerSocket classes:


Socket class Method


The Java.net.Socket class represents a socket that both the client and the server use to communicate with each other. The client wants to get a socket object through instantiation, while the service

a socket object is obtained via the Accept () method The return value.


The socket class has five construction methods:



When the socket construction method returns, and does not simply instantiate a socket object, it will actually attempt to connect to the specified server and port.


Here are some interesting ways to note that both the client and server side have a socket object, so both the client and the service side can call

These methods.


methods of the InetAddress class


This class represents an Internet Protocol (IP) address. The following is a list of the more useful methods for socket programming:


Socket Client Instance


The following greetingclient is a client program that connects to the server via the socket and sends a request, and then waits for a response.

FileName greetingserver.javaimport java.net.*;import java.io.*;p ublic class Greetingserver extends thread{private ServerS   Ocket ServerSocket;      public greetingserver (int port) throws ioexception{ServerSocket = new ServerSocket (port);   Serversocket.setsotimeout (10000); public void Run () {while (true) {try{System.out.println (' Waiting for client ' on port ' +serverso            Cket.getlocalport () + "...");            Socket Server = Serversocket.accept ();            System.out.println ("Just connected to" + server.getremotesocketaddress ());            DataInputStream in =new DataInputStream (Server.getinputstream ());            System.out.println (In.readutf ());            DataOutputStream out =new DataOutputStream (Server.getoutputstream ());            Out.writeutf ("Thank-Connecting to" + server.getlocalsocketaddress () + "\ngoodbye!");         Server.close ();    }catch (sockettimeoutexception s) {System.out.println ("Socket timed out!");        Break            }catch (IOException e) {e.printstacktrace ();         Break      }}} public static void Main (String [] args) {int port = Integer.parseint (Args[0]);         try {Thread t = new greetingserver (port);      T.start ();      }catch (IOException e) {e.printstacktrace (); }   }}

Compile in Java code and execute the following command to start the service with a port number of 6066:

$ java greetingserver 6066

Waiting for client on port 6066 ...


Turn on the client as follows:

$ java greetingclient localhost 6066

Connecting to localhost on port 6066

Just connected to localhost/127.0.0.1:6066

Server says Thank for connecting to/127.0.0.1:6066

goodbye!


The last one does not understand!!!

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.