Packages required for Java Network programming: java.net java.io Java.lang
Class or interface required in java.net: Socket serversocket datagramsocket datagrampacket URL urlconnection
Class or interface required in java.io: Inputstream/outputstream bufferedinputstream/bufferedoutputstream datainputstream/ DataOutputStream Bufferedreader/printwriter Objectinputstream/objectoutputstream
Class or interface required in Java.lang: Thread Runnable
First, the difference between the TCP protocol (Transmission Control Protocol) and the UDP protocol (User datagram protocols) is solved .
1.TCP is a connection-oriented protocol, UDP is a no-connection protocol, TCP can only transfer data when the server and the client establish a connection.
2. reliability, TCP after establishing a connection to transmit data, provide a guarantee of delivery, UDP just send the data out, the packet includes the full destination address and source address, determined by their own routing, so there is no guarantee that the data transfer success.
3. sequential, TCP protocol transmits data, the receiver receives the data is consistent with the order of delivery, UDP is not sequential.
4. speed, UDP transmission speed is faster than TCP.
5. data boundaries, TCP does not have data boundaries.
6.TCP is heavyweight, UDP is lightweight.
7.TCP has a larger header than UDP. The header size of the TCP packet is typically 20 bytes, which is twice times more than 8 bytes, and the UDP datagram is grouped by the header sizes. The TCP header contains the serial number, confirmation number, data offset, hold, control bit, window, emergency pointer, select, fill, checksum, source port and destination port. The UDP header contains only the length, source port, destination port, checksum.
8.TCP does traffic control. TCP requires three guarantees to establish a socket connection before any user can send the data. TCP processing reliability and congestion control. On the other hand, UDP does not have options for flow control.
9. Use TCP, if you can not afford to lose any messages, and UDP is a transmission for high-speed data, where the loss of a single packet is acceptable, such as better video streaming or online multiplayer games.
Client:
1. Create a socket, initiate a request
2. Get the input or output stream from the socket InputStream Outputstram
3. Packaging flow
4. Read and write operations
When the client makes a write, the request is sent to the server (the server responds before the program is blocked), and then the read operation reads the server information.
5. Releasing resources (streams and sockets)
Instance (use the socket to connect the client to the server side and get the server's time)
Tcpclient.java
Import Java.io.BufferedReader;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import Java.io.PrintWriter;
Import java.net.InetAddress;
Import Java.net.Socket;
public class TcpClient {
public static void Main (string[] args) {
Socket Client=null;
PrintWriter Pw=null;
BufferedReader Br=null;
try {
Build sockets
Client=new Socket ("localhost", 8888);
Get input and output stream
OutputStream Os=client.getoutputstream ();
InputStream Is=client.getinputstream ();
Packaging
Pw=new printwriter (OS);
Br=new BufferedReader (New InputStreamReader (IS));
Pw.println ("I ' M" +inetaddress.getlocalhost (). GetHostName () + "Please give me your time:");
Pw.flush ();
The program will block
String Msg=br.readline ();
SYSTEM.OUT.PRINTLN (msg);
} catch (Exception e) {
E.printstacktrace ();
}finally{
try {
if (pw!=null) pw.close ();
if (br!=null) br.close ();
if (client!=null) client.close ();
} catch (Exception e) {
E.printstacktrace ();
}
}
}
}
Tcpserver.java
Import Java.io.BufferedReader;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.io.PrintWriter;
Import Java.net.ServerSocket;
Import Java.net.Socket;
Import java.util.Date;
public class TCPServer {
public static void Main (string[] args) {
ServerSocket Server=null;
Socket Client=null;
PrintWriter Pw=null;
BufferedReader Br=null;
try {
Build ServerSocket
Server=new ServerSocket (8888);
Using the Accept method to get the socket from the client
while (true) {
Client=server.accept ();
Get input and output stream
Br=new BufferedReader (New InputStreamReader (Client.getinputstream ()));
Pw=new PrintWriter (New OutputStreamWriter (Client.getoutputstream ()));
Read and write operations
String Msg=br.readline ();
SYSTEM.OUT.PRINTLN (msg);
Date Date=new date ();
Pw.println ("Now is:" +date);
Pw.flush ();
Freeing resources
if (pw!=null) pw.close ();
if (br!=null) br.close ();
if (client!=null) client.close ();
}
} catch (Exception e) {
E.printstacktrace ();
}
}
}
Change the service side of the top to multithreaded processing
Serverthread.java
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.io.PrintWriter;
Import Java.net.Socket;
Import Java.util.Date;
public class Serverthread extends thread{
Private Socket client;
Public Serverthread (Socket client) {
This.client=client;
}
public void Run () {
try {
BufferedReader BR;
br = new BufferedReader (New InputStreamReader (Client.getinputstream ()));
PrintWriter PW;
PW = new PrintWriter (New OutputStreamWriter (Client.getoutputstream ()));
Read and write operations
String Msg=br.readline ();
SYSTEM.OUT.PRINTLN (msg);
Date Date=new date ();
Pw.println ("Now is:" +date);
Pw.flush ();
Sleep (100);
Freeing resources
if (pw!=null) pw.close ();
if (br!=null) br.close ();
if (client!=null) Client.close ();}
catch (Exception e) {
E.printstacktrace ();
}
}
}
Use a dead loop in server to accept client requests and start the Serverthread thread
Tcpserver.java
Import Java.io.BufferedReader;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.io.PrintWriter;
Import Java.net.ServerSocket;
Import Java.net.Socket;
Import Java.util.Date;
public class TCPServer {
public static void Main (string[] args) {
ServerSocket Server=null;
Socket Client=null;
try {
Build ServerSocket
Server=new ServerSocket (8888);
Using the Accept method to get the socket from the client
while (true) {
Client=server.accept ();
New Serverthread (client). Start ();
}
} catch (Exception e) {
E.printstacktrace ();
}
}
}
URL Connections
Create URL
URL url=new url ("http://www.baidu.com")
URLConnection Conn=url. OpenConnection ()
Connecting to a server
Conn.connect ()
Conn.getheaderfieldkey (N)
Conn.getheaderfield (N)
Get an input stream and encapsulate it
BufferedReader in=new BufferedReader (New InputStreamReader (Conn.getinputstream ()))
Reading information from the stream
Line=in.readline ()
Java Network Notes