Java _ Network Programming

Source: Internet
Author: User

L Network Model
OSI reference model
TCP/IP Reference Model
L network communication elements
IP address
Port Number
Transmission Protocol


Network Reference Model

 


Network communication elements
LIP address: InetAddress
Identifier of the device in the Network
Hard to remember, available Host Name
Local loopback address: 127.0.0.1 Host Name: localhost
L port number
Used to identify the logical address of a process.
Valid port: 0 ~ 65535, 0 ~ 1024 the system uses or retains the port.
L transmission protocol
Communication rules
Common protocols: TCP and UDP


TCP and UDP
LUDP
Encapsulate data and source and target data into data packets without establishing a connection
The size of each datagram is limited to 64 KB.
Because there is no connection, It is an unreliable Protocol
Fast connection is not required
LTCP
Establish a connection to form a channel for data transmission.
Transfer large data volume in connection
The connection is a reliable protocol that uses three-way handshakes.
A connection is required, which is less efficient.

Socket
LSocket is a mechanism provided for network services.
L both ends of the communication have sockets.
L network communication is actually the communication between sockets.
L data is transmitted through IO between two sockets.

UDP Transmission
Lw.ramsocket and DatagramPacket
L establish the sender and acceptor.
L create a data packet.
L call the sending and receiving method of the Socket.
L disable Socket.
The sender and acceptor are two independent programs.

Sender
L At the sender end, the destination IP address and port must be specified in the data packet object.
DatagramSocket ds = new DatagramSocket ();
Byte [] by = "hello, udp". getBytes ();
DatagramPacket dp = new DatagramPacket (by, 0, by. length,
InetAddress. getByName ("127.0.0.1"), 10000 );
Ds. send (dp );
Ds. close ();

Acceptor
L at the receiving end, specify the listening port.
DatagramSocket ds = new DatagramSocket (10000 );
Byte [] by = new byte [1024];
DatagramPacket dp = new DatagramPacket (by, by. length );
Ds. receive (dp );
String str = new String (dp. getData (), 0, dp. getLength ());
System. out. println (str + "--" + dp. getAddress ());
Ds. close ();

Tcp transmission is the most prone to Problems
L The client is connected to the server and both ends are waiting without any data transmission.
L routine analysis:
Because the read method or readLine method is blocking.
L solution:
Custom end tag
Use the shutdownInput and shutdownOutput methods.

Demonstrate tcp transmission.
1. tcp is divided into clients and servers.
2. The client corresponds to a Socket.
The server object is ServerSocket.

Client,
By checking the socket object, you can connect to the specified host when the object is created.
Because tcp is connection-oriented. Therefore, when establishing the socket service,
The server must exist and the connection is successful. After a channel is formed, data is transmitted through the channel.

Requirement: Send text data to the server.

Steps:
1. Create a Socket service. Host and port to be connected.

Import java. io .*;
Import java.net .*;
Class TcpClient
{
Public static void main (String [] args) throws Exception
{
// Create the socket service of the client. Specify destination host and Port
Socket s = new Socket ("192.168.1.254", 10003 );
// To send data, the output stream in the socket stream should be obtained.
OutputStream out = s. getOutputStream ();
Out. write ("tcp ge men lai le". getBytes ());
S. close ();
}
}


Requirement: Define the terminal to receive data and print it on the console.
Server:
1. Create a socket service for the server. ServerSocket ();
And listen to a port.
2. Obtain the connected client object.
Use the accept method of ServerSokcet. This method is blocked because no connection is available.
3. If the client sends data, the server uses the corresponding client object and obtains the read stream of the client object to read the sent data.
And print it on the console.
4. Disable the server. (Optional)

Class TcpServer
{
Public static void main (String [] args) throws Exception
{
// Create a socket service on the server. And listen to a port.
ServerSocket ss = new ServerSocket (10003 );

// Obtain the client object connected by using the accept method.
While (true)
{
Socket s = ss. accept ();

String ip = s. getInetAddress (). getHostAddress ();
System. out. println (ip + "... connected ");

// Obtain the data sent from the client. Use the read stream of the client object to read the data.
InputStream in = s. getInputStream ();
Byte [] buf = new byte [1, 1024];
Int len = in. read (buf );
System. out. println (new String (buf, 0, len ));
S. close (); // close the client.
}
// Ss. close ();
}
}
Bytes -----------------------------------------------------------------------------------------------
Import java. io .*;
Import java.net .*;
/*
This example shows the mutual access between the client and the server of tcp transmission.
Requirement: the client sends data to the server. After receiving the data, the server sends feedback to the client.

Client:
1. Establish the socket service. Specify the host and port to be connected.
2. Obtain the output stream in the socket stream. Write Data to the stream. It is sent to the server over the network.
3. Obtain the input stream from the socket stream, obtain and print the data feedback from the server.
4. disable Client resources.

Class TcpClient2
{
Public static void main (String [] args) throws Exception
{
Socket s = new Socket ("192.168.1.254", 10004 );
OutputStream out = s. getOutputStream ();
Out. write ("server, hello". getBytes ());

InputStream in = s. getInputStream ();

Byte [] buf = new byte [1, 1024];
Int len = in. read (buf );
System. out. println (new String (buf, 0, len ));
S. close ();
}
}

Class TcpServer2
{
Public static void main (String [] args) throws Exception
{
ServerSocket ss = new ServerSocket (10004 );
Socket s = ss. accept ();
String ip = s. getInetAddress (). getHostAddress ();
System. out. println (ip + "... connected ");
InputStream in = s. getInputStream ();
Byte [] buf = new byte [1, 1024];
Int len = in. read (buf );
System. out. println (new String (buf, 0, len ));
OutputStream out = s. getOutputStream ();
Thread. sleep (10000 );
Out. write ("buddy received, you can also". getBytes ());
S. close ();
Ss. close ();
}
}
Bytes ----------------------------------------------------------------------------------------------


Write a chat program.
It contains the part of the received data and the part of the sent data.
These two parts must be executed simultaneously.
The multithreading technology is required.
One thread controls receiving and one thread controls sending.

Because the receiving and sending actions are inconsistent, we need to define two run methods.
The two methods must be encapsulated into different classes.

Import java. io .*;
Import java.net .*;
Class Send implements Runnable
{
Private DatagramSocket ds;
Public Send (DatagramSocket ds)
{
This. ds = ds;
}

Public void run ()
{
Try
{
BufferedReader bufr = new BufferedReader (new InputStreamReader (System. in ));
String line = null;
While (line = bufr. readLine ())! = Null)
{
Byte [] buf = line. getBytes ();
DatagramPacket dp =
New DatagramPacket (buf, buf. length, InetAddress. getByName ("192.168.1.255"), 10002 );
Ds. send (dp );
If ("886". equals (line ))
Break;
}
}
Catch (Exception e)
{
Throw new RuntimeException ("sender failed ");
}
}
}

Class Rece implements Runnable
{
Private DatagramSocket ds;
Public Rece (DatagramSocket ds)
{
This. ds = ds;
}
Public void run ()
{
Try
{
While (true)
{
Byte [] buf = new byte [1, 1024];
DatagramPacket dp = new DatagramPacket (buf, buf. length );
Ds. receive (dp );
String ip = dp. getAddress (). getHostAddress ();
String data = new String (dp. getData (), 0, dp. getLength ());
If ("886". equals (data ))
{
System. out. println (ip + "... leave the chat room ");
Break;
}
System. out. println (ip + ":" + data );
}
}
Catch (Exception e)
{
Throw new RuntimeException ("acceptor failed ");
}
}
}

Class ChatDemo
{
Public static void main (String [] args) throws Exception
{
DatagramSocket sendSocket = new DatagramSocket ();
DatagramSocket receSocket = new DatagramSocket (10002 );

New Thread (new Send (sendSocket). start ();
New Thread (new Rece (receSocket). start ();
}
}

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.