Java Network programming

Source: Internet
Author: User

1. IP, domain name, port number concept 1.1 IP

IP (Internet Protocol) is the basic protocol of the Internet, and one of the functions is to assign an IP address to a device (host) in the Internet to find a device in the Internet

IP addresses starting with 127 are called local loopback addresses, such as 127.0.0.1, which represent native IP addresses, and are primarily useful for local testing

The packet is the basic unit of data transmission in the Internet, which specifies how the data is fragmented and how a single packet is transferred to the target host so that the data can be exchanged between the various devices

1.2 Domain name

The IP address is not convenient to remember, and the domain name, is the name of the host on the Internet, each domain name corresponds to an IP address, and the domain name is convenient to remember, so people generally use the domain name to access a host

localhost indicates the name of the local host, corresponding to the 127.0.0.1

DNS (domain Name System), which holds the correspondence between all domain names and IP addresses on the Internet, when people use a domain name, they need to first query the IP address of the domain name through DNS, and then use the IP address to locate the target host

The Hosts file in the computer is a local DNS (C:\WINDOWS\SYSTEM32\DRIVERS\ETC directory), we can modify the Hosts file manually configure the domain name and IP address of the corresponding relationship, the computer will look for the hosts file first

1.3 Port number

A host can provide a variety of services (running multiple programs), in order to facilitate the outside distinction and access, each service must have a port number, through the IP address and port number to uniquely determine a host on a service

The range of port numbers is [0, 65535], where [0, 1023] is the system reserved port, which is provided to the system service as well as other famous services such as HTTP (80). Our own programs do not occupy the system reserved ports if they do not provide a well-known service

A port number in the host can only be occupied by one program at a time, the system is allocated by first requesting first, the end of the program is the port number

A port number is sometimes used by other programs, or the program repeats itself when it newspapers the number of errors, you can perform Netstat-ano on the cmd command line to see the process ID of the program that occupies a port number, and then find the process to end it in Task Manager.

2. TCP

TCP (transmission Control Protocol) transmission protocol, is a connection-oriented, reliable, byte-stream-based Transport Layer communication protocol, many application layer protocols are based on TCP, the program can also directly use TCP for network communication.

TCP will establish a connection between the two hosts (virtual), through a certain way to control the process of data transmission, you can ensure the complete, orderly, correct

3. Socket programming

Network programming, mainly refers to TCP-based network communication programming, using the socket class implementation, also known as socket programming

The socket programming model has the server side and the client, the server side uses the ServerSocket to create, generally has the fixed IP address and the port number, facilitates provides the service to the outside world. The client can have multiple, and use the socket to actively connect to the server. Once connected, the server side also creates a socket object that represents this connection

Programming Steps:

Server-side:

1 Creating a Server object ServerSocket

2 waits for a connection request from the client, returns the socket object that represents the connection when the request is received

3 Open a new thread to handle this connection specifically

4 Get the connected input and output stream and exchange data according to certain rules

5 Close the connection (the IO stream is automatically closed when the connection is closed)

Client:

1 Create a Socket object, which is to request a connection to the server

2 Get the connected input and output stream and exchange data according to certain rules

3 Closing the connection at last (the IO stream is automatically closed when the connection is closed)

Usually programming is based on the application layer protocol, such as HTTP, direct socket programming is not much. However, since socket programming is an important technology at the basic level, it is imperative to master

 Public class Server1 {    publicstaticvoidthrows  IOException {         New ServerSocket (10001);         = server.accept ();         = Socket.getinputstream ();         = Socket.getoutputstream ();         byte [] data = "Hello". GetBytes ();        Outputstream.write (data);        Socket.close ();    }}

 Public classClient1 { Public Static voidMain (string[] args)throwsIOException {Socket Socket=NewSocket ("localhost", 10001); InputStream InputStream=Socket.getinputstream (); OutputStream OutputStream=Socket.getoutputstream (); byte[] Buff =New byte[1024]; intLen =inputstream.read (Buff); System.out.println (NewString (Buff, 0, Len));    Socket.close (); }}

To perform the steps:

1. Running Server1

2. Running Client1

3. Output

Hello
3.1 String rollover server based on socket implementation
/** Flip the character of a row of data read from the client and send it to the client * when reading to over, the connection is disconnected*/ Public classServer2 { Public Static voidMain (string[] args) {Try{serversocket server=NewServerSocket (10002);  while(true) {Socket Socket=server.accept (); MyThread MyThread=NewMyThread (socket);            Mythread.start (); }        } Catch(IOException e) {e.printstacktrace (); }    }}classMyThreadextendsThread {Privatesocket socket;  PublicMyThread (socket socket) { This. Socket =socket; } @Override Public voidrun () {Try{BufferedReader BufferedReader=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); BufferedWriter BufferedWriter=NewBufferedWriter (NewOutputStreamWriter (Socket.getoutputstream ())); String Line=NULL;  while(line = Bufferedreader.readline ())! =NULL) {                if("Over". Equalsignorecase (line)) {                     Break; }                //action for character rollover                Char[] CHS =Line.tochararray ();  for(inti = 0; i < CHS.LENGTH/2; i++) {                    CharCH =Chs[i]; Chs[i]= Chs[chs.length-1-i]; Chs[chs.length-1-i] =ch;                } bufferedwriter.write (CHS);                Bufferedwriter.newline ();            Bufferedwriter.flush (); }        } Catch(Exception e) {e.printstacktrace (); } finally {            Try{socket.close (); } Catch(IOException e) {e.printstacktrace (); }        }    }}
View code-string rollover service side
 Public classClient2 { Public Static voidMain (string[] args) {socket socket=NULL; Scanner Scanner=NULL; Try{Socket=NewSocket ("localhost", 10002); BufferedReader BufferedReader=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); BufferedWriter BufferedWriter=NewBufferedWriter (NewOutputStreamWriter (Socket.getoutputstream ())); Scanner=NewScanner (system.in); String Line=NULL;  while(line = Scanner.nextline ())! =NULL) {bufferedwriter.write (line);                Bufferedwriter.newline ();                Bufferedwriter.flush (); Line=Bufferedreader.readline (); if(line = =NULL) {                     Break;            } System.out.println (line); }        } Catch(Exception e) {e.printstacktrace (); } finally {            Try {                if(Socket! =NULL) {socket.close (); }            } Catch(IOException e) {e.printstacktrace (); }            if(Scanner! =NULL) {scanner.close (); }        }    }}
View code-string Rollover client4. UDP-based network programming

In addition to TCP, the Transport Layer protocol also has UDP (user Datagram Protocol), which is the Subscriber datagram protocol. UDP is non-connected, and does not guarantee the complete and orderly data, but the transmission efficiency is very high, suitable for video, audio and other data reliability requirements of the scene is not too high

UDP programming when there is no typical server-client structure, and the two ends of the communication does not establish a connection, you can directly encapsulate the data into a packet sent to the other end, and each end can send, receive packets

Datagramsocket represents one end of the communication and can send and receive packets

Datagrampacket packet, theoretically a packet can contain up to 65535 bytes of data

 Public class Send1 {    publicstaticvoidthrows  ioexception {          New Datagramsocket (10003);         byte [] data = "Hello". GetBytes ();         New Datagrampacket (data, Data.length, Inetaddress.getlocalhost (), 10004);        Sendsocket.send (packet);        Sendsocket.close ();    }}
View Code-send1
 Public classReceive1 { Public Static voidMain (string[] args)throwsIOException {datagramsocket receivesocket=NewDatagramsocket (10004); byte[] Buff =New byte[1024]; Datagrampacket Packet=Newdatagrampacket (Buff, buff.length);        Receivesocket.receive (packet); intLen =packet.getlength (); System.out.println (NewString (Buff, 0, Len));    Receivesocket.close (); }}
View code-received

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.