Java Java Network Programming rookie advanced: Getting Started with TCP and sockets

Source: Internet
Author: User

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:

  1. Public class TCPServer implements Runnable {
  2. private ServerSocket ServerSocket;
  3. Public tcpserver (int port) throws IOException {
  4. //Create a passive socket for a TCP server bound to a port.
  5. ServerSocket = New ServerSocket (port);
  6. }
  7. @Override
  8. public Void Run () {
  9. While (true) {
  10. try {
  11. //Accept a client connection in a blocking manner, returning an active socket that represents the connection.
  12. Socket socket = serversocket.accept ();
  13. //Handle client connections in a new thread.
  14. New Thread (new ClientHandler (socket)). Start ();
  15. } catch (IOException ex) {
  16. Ex.printstacktrace ();
  17. }
  18. }
  19. }
  20. }
  21. Public class ClientHandler implements Runnable {
  22. private socket socket;
  23. Public ClientHandler (socket socket) {
  24. This.socket = objects.requirenonnull (socket);
  25. }
  26. @Override
  27. public Void Run () {
  28. try (socket s = socket) { ///Reduce the amount of code tricks ...
  29. //wraps the input stream of the socket to read the lines of text sent by the client.
  30. BufferedReader in = new BufferedReader (new InputStreamReader (
  31. S.getinputstream (), standardcharsets.utf_8));
  32. //wraps the output stream of the socket to send the conversion result to the client.
  33. PrintWriter out = new PrintWriter (new OutputStreamWriter (
  34. S.getoutputstream (), standardcharsets.utf_8), true);
  35. String line = null;
  36. While (line = In.readline ()) = null) {
  37. if (line.equals ("Bye")) {
  38. Break ;
  39. }
  40. //outputs the conversion result to the client.
  41. Out.println (Line.touppercase (locale.english));
  42. }
  43. } catch (IOException ex) {
  44. Ex.printstacktrace ();
  45. }
  46. }
  47. }

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:

  1. Public class TcpClient implements Runnable {
  2. private socket socket;
  3. Public TcpClient (String host, int port) throws IOException {
  4. //Create a socket attached to the server.
  5. Socket = new socket (host, port);
  6. }
  7. @Override
  8. public Void Run () {
  9. try (socket s = socket) { //reduce the amount of code again ...
  10. //wraps the output stream of the socket to send a line of text to the server.
  11. PrintWriter out = new PrintWriter (new OutputStreamWriter (
  12. S.getoutputstream (), standardcharsets.utf_8), true);
  13. //wraps the input stream of the socket to read the text rows returned by the server.
  14. BufferedReader in = new BufferedReader (new InputStreamReader (
  15. S.getinputstream (), standardcharsets.utf_8));
  16. Console console = System.Console ();
  17. String line = null;
  18. While (line = Console.ReadLine ()) = null) {
  19. if (line.equals ("Bye")) {
  20. Break ;
  21. }
  22. //Send text lines to the server.
  23. Out.println (line);
  24. the text line returned by the//print server.
  25. Console.writer (). println (In.readline ());
  26. }
  27. //Notifies the server to close the connection.
  28. Out.println ("Bye");
  29. } catch (IOException ex) {
  30. Ex.printstacktrace ();
  31. }
  32. }
  33. }

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

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.