Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to get started with TCP and sockets in Java

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about how to get started with TCP and sockets in Java. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.

JDK provides support for two data transmission protocols, TCP (Transmission Control Protocol, Transmission Control Protocol) and UDP (User Datagram Protocol, user Datagram Protocol). This article begins to explore TCP.

Basic knowledge of TCP

In the "server-client" architecture, the server and client each maintain an endpoint, and the two endpoints need to exchange data over the network. TCP provides a reliable streaming connection for this requirement, which means that the data sent and received are consecutive bytes, and there is no limit on the size of the data. An endpoint consists of an IP address and a port (technical term is "tuple {IP address, port}"). In this way, a connection can be represented by tuple {local address, local port, remote address, remote port}.

Connection process

In the TCP programming interface, endpoints are represented as TCP sockets. There are two types of TCP sockets: active and passive, and the "passive" state is often referred to as the "listening" state. The process for the server and client to connect using sockets is as follows:

1. The server creates a passive socket and begins to listen for client connections in a loop.

2. The client creates an active socket to connect to the server.

3. The server accepts the connection from the client and creates an active socket that represents the connection.

4. The server and client transfer data through the two active sockets created in steps 2 and 3.

The following is an illustration of the connection process:

A simple TCP server

JDK provides the ServerSocket class to represent the passive socket of the TCP server. The following code demonstrates a simple TCP server (multithreaded blocking mode) that constantly listens and accepts connections from the client, then reads the text sent by the client by line, converts the full text to uppercase and returns it to the client until the client sends the text line bye:

Public class TcpServer implements Runnable {private ServerSocket serverSocket; public TcpServer (int port) throws IOException {/ / creates a TCP server passive socket bound to a port. ServerSocket = new ServerSocket (port);} @ Override public void run () {while (true) {try {/ / accepts a client connection in a blocking manner and returns an active socket representing the connection. Socket socket = serverSocket.accept (); / / handles 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) {/ / tricks to reduce the amount of code. / / 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 } / / output the conversion result to the client. Out.println (line.toUpperCase (Locale.ENGLISH));} catch (IOException ex) {ex.printStackTrace ();}

Blocking mode is simple to program, but there are performance problems because the server thread gets stuck in accepting the client's accept () method and cannot make efficient use of resources. Sockets support non-blocking mode, which is skipped for now.

A simple TCP client

JDK provides the Socket class to represent the active socket of the TCP client. The following code demonstrates the client of the above server:

Public class TcpClient implements Runnable {private Socket socket; public TcpClient (String host, int port) throws IOException {/ / create a socket that connects to the server. Socket = new Socket (host, port);} @ Override public void run () {try (Socket s = socket) {/ / reduce the code again. / / wraps the output stream of the socket to send lines 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 lines of text 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 lines of text to the server. Out.println (line); / / print the line of text returned by the server. Console.writer (). Println (in.readLine ());} / / tells the server to close the connection. Out.println ("bye");} catch (IOException ex) {ex.printStackTrace ();}

As you can see from the JDK documentation, ServerSocket and Socket can set some parameters and support delayed binding when initializing. These things have an impact on performance and behavior. The next two articles will explain the initialization of these two classes in detail.

After reading the above, do you have any further understanding of how to get started with TCP and sockets in Java? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report