Java Network Programming Rookie advanced: Getting Started with TCP and sockets
The JDK provides support for two data transfer protocols, TCP (transmission Control Protocol, transmission Protocol), and UDP (user Datagram Protocol, Subscriber Datagram Protocol). This article begins with the discussion of TCP.
TCP Basic Knowledge
In the server-client architecture, the server and the client each maintain an endpoint, and two endpoints need to exchange data over the network. TCP provides a reliable streaming connection for this requirement, which means that both outgoing and received data are contiguous bytes, and there is no size limit on the amount of data. An endpoint is comprised of an IP address and a port (the professional term is "tuple {IP address, port}"). In this way, a connection can be represented by a tuple {local address, local port, remote address, remote port}.
Connection process
In the TCP programming interface, the endpoint is represented as a TCP socket. There are two types of TCP sockets: Active and passive, and the "passive" state is often referred to as the "listening" state. The process by which servers and clients connect using sockets is as follows:
1. The server creates a passive socket and begins looping the connection of the client listening.
2. The client creates an active socket to connect to the server.
3. The server accepts the client connection and creates an active socket that represents the connection.
4. The server and client transmit data via two active sockets created in steps 2 and 3.
Here is a diagram of the connection process:
A simple TCP server
The JDK provides a passive socket for the ServerSocket class to represent the TCP server. The following code demonstrates a simple TCP server (multi-threaded blocking mode) that constantly listens for and accepts connections from clients, then reads the text sent by the client in rows and returns it to the client after the full-text is converted to uppercase until the client sends a text line bye:
- Public class TCPServer implements Runnable {
- private ServerSocket ServerSocket;
- Public tcpserver (int port) throws IOException {
- //Create a passive socket for a TCP server bound to a port.
- ServerSocket = New ServerSocket (port);
- }
- @Override
- public Void Run () {
- While (true) {
- try {
- //Accept a client connection in a blocking manner, returning an active socket that represents the connection.
- Socket socket = serversocket.accept ();
- //Handle client connections in a new thread.
- New Thread (new ClientHandler (socket)). Start ();
- } catch (IOException ex) {
- Ex.printstacktrace ();
- }
- }
- }
- }
- Public class ClientHandler implements Runnable {
- private socket socket;
- Public ClientHandler (socket socket) {
- This.socket = objects.requirenonnull (socket);
- }
- @Override
- public Void Run () {
- try (socket s = socket) { ///Reduce the amount of code tricks ...
- //wraps the input stream of the socket to read the lines of text sent by the client.
- BufferedReader in = new BufferedReader (new InputStreamReader (
- S.getinputstream (), standardcharsets.utf_8));
- //wraps the output stream of the socket to send the conversion result to the client.
- PrintWriter out = new PrintWriter (new OutputStreamWriter (
- S.getoutputstream (), standardcharsets.utf_8), true);
- String line = null;
- While (line = In.readline ()) = null) {
- if (line.equals ("Bye")) {
- Break ;
- }
- //outputs the conversion result to the client.
- Out.println (Line.touppercase (locale.english));
- }
- } catch (IOException ex) {
- Ex.printstacktrace ();
- }
- }
- }
Blocking mode is simple to program, but has performance problems because the server thread is stuck on the Accept () method of the receiving client and cannot effectively utilize the resource. Sockets support nonblocking mode, which is now temporarily skipped.
A simple TCP client
The JDK provides the socket class to represent the active socket of the TCP client. The following code shows the client for the above server:
- Public class TcpClient implements Runnable {
- private socket socket;
- Public TcpClient (String host, int port) throws IOException {
- //Create a socket attached to the server.
- Socket = new socket (host, port);
- }
- @Override
- public Void Run () {
- try (socket s = socket) { //reduce the amount of code again ...
- //wraps the output stream of the socket to send a line of text to the server.
- PrintWriter out = new PrintWriter (new OutputStreamWriter (
- S.getoutputstream (), standardcharsets.utf_8), true);
- //wraps the input stream of the socket to read the text rows returned by the server.
- BufferedReader in = new BufferedReader (new InputStreamReader (
- S.getinputstream (), standardcharsets.utf_8));
- Console console = System.Console ();
- String line = null;
- While (line = Console.ReadLine ()) = null) {
- if (line.equals ("Bye")) {
- Break ;
- }
- //Send text lines to the server.
- Out.println (line);
- the text line returned by the//print server.
- Console.writer (). println (In.readline ());
- }
- //Notifies the server to close the connection.
- Out.println ("Bye");
- } catch (IOException ex) {
- Ex.printstacktrace ();
- }
- }
- }
As you can see from the JDK documentation, ServerSocket and sockets can be initialized with some parameters, and delay binding is also supported. These things have an impact on performance and behavior. The next two articles will explain the initialization of these two classes separately.
Original link: http://www.blogjava.net/shinzey/archive/2012/01/04/367846.html