about TCP and UDP protocols
TCP: is a connection-oriented protocol that guarantees reliable transmission. Through the TCP protocol transmission, obtains is a sequential error-free data stream. A connection must be established between the pair of two sockets of the sender and receiver to communicate on the basis of the TCP protocol, and when one socket (usually the server socket) waits for the connection to be made, another socket can require a connection. Once these two sockets are connected, they can be transmitted in both directions, and both can be sent or received.
UDP: is a connectionless protocol, each datagram is a separate information, including the full source address or destination address, it on the network on any possible path to the destination, so whether to reach the destination, the time to arrive at the destination and the correctness of the content is not guaranteed.
Comparison:
TCP has great vitality in network communications, such as remote Connection (Telnet) and file Transfer (FTP) that require indefinite length of data to be transmitted reliably. But the reliable transmission is to pay the price, the test of the correctness of the data content must occupy the processing time of the computer and the bandwidth of the network, so the TCP transmission efficiency is not as high as UDP.
UDP is simple and requires less monitoring, so it is usually used for client/server applications in decentralized systems with high reliability on the LAN. For example, video conferencing system, does not require audio and video data is absolutely correct, as long as the consistency can be guaranteed, in this case, the obvious use of UDP is more reasonable. Java Socket Programming
Two programs on the network realize the exchange of data through a two-way communication connection, one end of this two-way link is called a socket. The socket is typically used to implement a connection between the client and the service party. The socket is a very popular programming interface for the TCP/IP protocol, and a socket is uniquely determined by an IP address and a port number. In the Java environment, socket programming mainly refers to the network programming based on TCP/IP protocol. Socket Communication Process
The socket server listens for a connection request on a port. When the client issues a connect connection request and a connection is made to the IP and port on the server, the server will give the client the accept to accept the message. Four steps:
1. Create socket
ServerSocket serversocket = new ServerSocket (8090);
2. Open socket connection output and input stream
InputStream in = Socket.getinputstream (); Get input stream
outputstream out = Socket.getoutputstream ();//Get output stream
3. Read and Write Data
Read the input stream using Bufferreader
bufferedreader reader = new BufferedReader (new InputStreamReader (in));
Print out output stream
printwriter writer = new PrintWriter (out, true);
Writer.println ("Thread ID:" + thread.currentthread (). GetId ());
Reads the input String line
= Reader.readline () of a row of clients;
4. Close socket
Serversocket.close ();
How to create a socket
The common method of creating sockets is in the java.net package. Provides some common ways to create:
Socket (inetaddress address, int port);
Socket (inetaddress address, int port, Boolean stream);
Socket (String host, int prot);
Socket (String host, int prot, Boolean stream);
Socket (Socetimpl impl)
Socket (String host, int port, inetaddress localaddr, int localport)
Socket (inetaddress address, int port, inetaddress localaddr, int localport)
ServerSocket (int port);
ServerSocket (int port, int backlog);
ServerSocket (int port, int backlog, inetaddress bindaddr) The biggest disadvantage of using Java socket directly
1. Directly using the socket for programming, because the socket is blocking , so if you write the code, you can not allow multiple users to connect to your server at the same time
2. If we adopt a threading approach to support multi-user (client) connections, but when the number of user connections is very much, it requires more than n threads , server performance will decline
look at a server-side socket Implementation example:
public class Test {public
static void Main (string[] args) {
System.out.println ("Java scoket Server Run ...");
//Create a fixed size thread pool
executorservice pool = executors.newfixedthreadpool (2);
ServerSocket serversocket = null;
try {
//start a 8090-port socket service
ServerSocket = new ServerSocket (8090);
while (true) {
socket socket = serversocket.accept ();//wait wait
pool.execute (new myrunable (socket));/thread pool
}
} catch (Exception e) {
} finally {
pool.shutdown ();//close thread pool
}
}
}
public class Myrunable implements Runnable {private socket socket = NULL;
Public myrunable (socket socket) {this.socket = socket;
@Override public void Run () {try {InputStream in = Socket.getinputstream ();//Get input stream OutputStream out = Socket.getoutputstream (); Get output stream//Read input stream using Bufferreader bufferedreader reader = new BufferedReader (New InputStreamReader (
in));
Print out output stream printwriter writer = new PrintWriter (out, true);
Writer.println ("Thread ID:" + thread.currentthread (). GetId ());
Reads the input String line = Reader.readline () of a row of clients; Exit while (!) if the client enters bye.
Bye ". Equals (line)] {writer.println (" ECHO: "+ line);
line = Reader.readline ();
} reader.close ();
Writer.close (); The catch (Exception e) {}}}
Simple Client Example:
public static void Main (string[] args) throws Unknownhostexception, IOException {String host = "192.168.136.100"; The service-side IP address to be connected int port = 8787;
The corresponding listener port for the server to be connected socket client = new socket (host, port);
InputStream in = Client.getinputstream ();
OutputStream out = Client.getoutputstream ();
String str = "Hello Wolrd[]woasodsadsadsad";
Out.write (Str.getbytes ());
byte[] bytes = new byte[1024];
int n = in.read (bytes);
System.out.println (New String (bytes, 0, n));
String str2 = "----------[]sadasdsad=======[]";
Out.write (Str2.getbytes ());
byte[] Bytes2 = new byte[1024];
int n2 = In.read (bytes2);
System.out.println (New String (bytes2, 0, N2));
byte[] Bytes3 = new byte[1024];
int n3 = In.read (BYTES3);
System.out.println (New String (Bytes3, 0, N3));
In.close ();
Client.close (); }
Java Nio Java NiO principle
NIO is non-blocking io.
1. NIO has a dedicated thread to handle multiple IO. This ensures the rational utilization of thread resources.
2. Event-driven form. The event is not triggered.
3. Thread communication: Threads communicate with each other through wait,notify. Ensure that each context switch is meaningful. Reduce unnecessary thread switching.
The important core modules of Java NiO
1. Channels
2. Buffers
3. Selectors
Channels is a bit like a stream, can write data to buffers, can also read to channels, can also read, mainly include: Filechannel,datagramchannel,socketchannel, Serversocketchannel. We will mainly serversocketchannel here.
Buffers contains: Bytebuffer,charbuffer,doublebuffer,floatbuffer,intbuffer,longbuffer,shortbuffe.
Selectors:selector allows multiple Channel to be processed in a single thread. Figure:
selector Four kinds of event names
| Event name |
corresponding value |
| Server-side Receive client connection events |
Selectionkey.op_accept (16) |
| Client Connection service-side events |
Selectionkey.op_connect (8) |
| Read Events |
Selectionkey.op_read (1) |
| Write events |
Selectionkey.op_write (4) |
Selector can detect events on one or more channels. For example, the selectionkey.op_connect of information from a client connection is detected, such as detecting events that can be read by the server.
For example, register a read event:
Channel.register (This.selector, Selectionkey.op_read); Registering a read time
A simple example of NIO server and client
public class Test {private Selector Selector;
protected Charset Charset = Charset.forname ("UTF-8");
protected Charsetencoder Charsetencoder = Charset.newencoder ();
protected Charsetdecoder Charsetdecoder = Charset.newdecoder ();
/** * Main function * @param args/public static void Main (String args[]) {try {
Test test2 = new test (); Test2.init (); Initialization of Test2.listen ();
Listen for a catch (IOException e) {System.out.println (E.getmessage ());
} private void Init () throws IOException {System.out.println ("Java Nio scoket Server Run ..."); selector = Selector.open (); Open selector Serversocketchannel Serverchannel = Serversocketchannel.open (); Obtain a socket channel serverchannel.configureblocking (FALSE);//Set Channel to Non-blocking Serverchannel.socket (). Bind (New Inetsocketaddress (9000)); Binding ports
Serverchannel.register (selector, selectionkey.op_accept);
Registers the Selectionkey.op_connect event.
private void Listen () throws IOException {while (true) {selector.select ();
Iterator ite = This.selector.selectedKeys (). iterator ();
while (Ite.hasnext ()) {Selectionkey key = (Selectionkey) ite.next ();
Ite.remove (); Accept the connection event, the Selectionkey.op_accept event registered above (key.isacceptable ()) {Serversocketchann
El Serverchannel = (serversocketchannel) key.channel ();
Socketchannel channel = Serverchannel.accept ();
Channel.configureblocking (FALSE);
Channel.write (Bytebuffer.wrap (New String ("Welcome to NiO Socket"). GetBytes ()); Channel.register (This.selector, Selectionkey.op_read);
Registers a read event System.out.println ("There is a client connection up"); Read time, above registered Selectionkey.op_read event} else if (Key.isreadable ()) {//When Channel
When there is data coming over, execute this side of the read code Socketchannel Socketchannel = (socketchannel) key.channel (); Bytebuffer Bytebuffer = bytebuffer.allocate (1024);
Read 1024 characters at a time bytebuffer.clear ();
Long i = Socketchannel.read (Bytebuffer);
if (i = = 1) {socketchannel.close ();//Read failed} else {
Read Bytebuffer.flip ();
byte[] bytes = new byte[bytebuffer.remaining ()];
Bytebuffer.get (bytes);
String BODY = new String (bytes, "UTF-8");
System.out.println (body);
Write back String x = "Hello";
byte[] response = x.getbytes (); Bytebuffer WriteBuffer = bytebuffer.allocate (response.length);
Writebuffer.put (response);
Writebuffer.flip ();
Socketchannel.write (WriteBuffer); }
}
}
}
}
}
Client:
public class Test3 {private Selector Selector;
protected Charset Charset = Charset.forname ("UTF-8");
protected Charsetdecoder Charsetdecoder = Charset.newdecoder ();
Private Socketchannel channel;
public static final Test3 test3 = new Test3 ();
public static void Main (String args[]) {try {new Thread (new Runnable () {@Override
public void Run () {try {Test3.test3.init ();//initialization Test3.test3.listen ();
Listen for a catch (IOException e) {System.out.println (E.getmessage ());
}}). Start ();
try {thread.sleep (5000); catch (Exception e) {} test3.write ("Yes..");
Send a data Test3.write ("Yes111"); The catch (IOException e) {System.Out.println (E.getmessage ());
} public void Init () throws IOException {this.selector = Selector.open ();
Obtain a socket Channel Channel = Socketchannel.open ();
Channel.configureblocking (FALSE); Channel.connect (New Inetsocketaddress ("127.0.0.1", 9000)); Connect to a port Channel.register (selector, selectionkey.op_connect); Register a Connection event} public void write (String str) throws IOException {Channel.write (Bytebuffer.wrap new String (
STR). GetBytes ());
public void Listen () throws IOException {while (true) {selector.select ();
Iterator ite = This.selector.selectedKeys (). iterator ();
while (Ite.hasnext ()) {Selectionkey key = (Selectionkey) ite.next ();
Ite.remove (); Whether to connect events, the Selectionkey.op_connect if (key.isconnectable ()) {Socketchannel Channel, registered above
= (Socketchannel) key.channel (); If you are connecting, complete the connection if (channel.isconnectionpending ()) {CHANNEL.F
Inishconnect ();
} channel.configureblocking (FALSE);
Channel.write (New String ("Hello World") (Bytebuffer.wrap) getBytes ()); Channel.register (This.selector, Selectionkey.op_read);
The connection was established successfully, registering a read event System.out.println ("Connected ..."); Read Event} else if (Key.isreadable ()) {Socketchannel Socketchannel = (socketchannel) ke
Y.channel ();
Bytebuffer Bytebuffer = bytebuffer.allocate (1024);
Bytebuffer.clear ();
Long i = Socketchannel.read (Bytebuffer);
if (i = = 1) {socketchannel.close ();
else {bytebuffer.flip (); String msg = Charsetdecoder.decode (bytebuffer). ToSTring ();
System.out.println ("msg:" + msg); }
}
}
}
}
}