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 use socket of JAVA

2025-03-06 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to use JAVA's socket". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use JAVA's socket".

Native socket communication mechanism in JAVA current environment

Jdk = = 1.8

Knowledge point

Connection processing of socket

Processing of input and output streams of IO

Request data format processing

Request model optimization

Scene

Here we take the simplest one-request-response model as an example, assuming that we now need to communicate with the baidu site.

Establish a socket connection

First, we need to establish a socket connection (core code)

Import java.net.InetSocketAddress;import java.net.Socket;import java.net.SocketAddress;// initialization socketSocket socket = new Socket (); / initialize remote connection address SocketAddress remote = new InetSocketAddress (host, port); / / establish connection socket.connect (remote); handle socket input and output streams

After successfully establishing the socket connection, we can obtain its input and output stream, and the essence of communication is the processing of the input and output stream. Through the input stream, the data uploaded from the network connection is read, and the local data is transmitted to the remote end through the output stream.

Socket connections are actually a bit like dealing with file streams in that they are IO operations.

The input and output stream codes are as follows:

/ / input stream InputStream in = socket.getInputStream (); / / output stream OutputStream out = socket.getOutputStream ()

With regard to the processing of IO streams, we generally use the corresponding wrapper classes to deal with IO streams. If we deal with it directly, we need to operate on byte [], which is relatively cumbersome. If we use the wrapper class, we can deal with it directly as string, int, and so on, which simplifies the operation of IO bytes.

The following wrapper classes are processed with BufferedReader and PrintWriter as input and output.

/ / get socket input stream private BufferedReader getReader (Socket socket) throws IOException {InputStream in = socket.getInputStream (); return new BufferedReader (new InputStreamReader (in));} / / get socket output stream private PrintWriter getWriter (Socket socket) throws IOException {OutputStream out = socket.getOutputStream (); return new PrintWriter (new OutputStreamWriter (out));} data request and response

With the socket connection and the IO input and output stream, it's time to send the request data to and get the response result of the request.

Because of the support of the IO wrapper class, we can transfer it directly in the format of a string, and the wrapper class helps us to load the data into the corresponding byte stream.

Because we have HTTP access with the baidu site, we do not need to define additional output formats. With the standard HTTP transport format, you can respond to requests (some specific RPC frameworks may have custom communication formats).

The requested data content is processed as follows:

Public class HttpUtil {public static String compositeRequest (String host) {return "GET / HTTP/1.1\ r\ n" + "Host:" + host + "\ r\ n" + "User-Agent: curl/7.43.0\ r\ n" + "Accept: * / *\ r\ n\ r\ n";}}

The code for sending request data is as follows:

/ / initiate request PrintWriter writer = getWriter (socket); writer.write (HttpUtil.compositeRequest (host)); writer.flush ()

The code for receiving response data is as follows:

/ / read response String msg;BufferedReader reader = getReader (socket); while ((msg = reader.readLine ())! = null) {System.out.println (msg);} result display

At this point, I've finished all the core code for creating connections, sending requests, and receiving responses under native socket.

The complete code is as follows:

Import java.io.*;import java.net.InetSocketAddress;import java.net.Socket;import java.net.SocketAddress;import com.test.network.util.HttpUtil;public class SocketHttpClient {public void start (String host, int port) {/ / initialize socket Socket socket = new Socket (); try {/ / set socket connection SocketAddress remote = new InetSocketAddress (host, port); socket.setSoTimeout (5000) Socket.connect (remote); / / initiate request PrintWriter writer = getWriter (socket); System.out.println (HttpUtil.compositeRequest (host)); writer.write (HttpUtil.compositeRequest (host)); writer.flush (); / / read response String msg; BufferedReader reader = getReader (socket) While ((msg = reader.readLine ())! = null) {System.out.println (msg);}} catch (IOException e) {e.printStackTrace ();} finally {try {socket.close ();} catch (IOException e) {e.printStackTrace () }} private BufferedReader getReader (Socket socket) throws IOException {InputStream in = socket.getInputStream (); return new BufferedReader (new InputStreamReader (in));} private PrintWriter getWriter (Socket socket) throws IOException {OutputStream out = socket.getOutputStream (); return new PrintWriter (new OutputStreamWriter (out));}}

Next, we show the results of socket communication by instantiating a client.

Public class Application {public static void main (String [] args) {new SocketHttpClient () .start ("www.baidu.com", 80);}}

Result output:

Request model optimization

In this way, although there is no problem with implementing the function. But when we take a closer look, we find that IO blocking occurs during the IO write and read process. That is:

/ / IO blocking writer.write (HttpUtil.compositeRequest (host)); reader.readLine ()

So if you want to request 10 different sites at the same time, as follows:

Public class SingleThreadApplication {public static void main (String [] args) {/ / HttpConstant.HOSTS is the site collection for (String host: HttpConstant.HOSTS) {new SocketHttpClient () .start (host, HttpConstant.PORT);}

It must be the end of the first request response before the next site processing is initiated.

This is more obvious on the server side, although the code here is a client connection, but the specific operation is similar to the server side. Requests can only be processed one by one, which is definitely not up to standard in terms of response time.

Multithreaded processing

Some people think that this is not a problem at all. JAVA is a multithreaded programming language. In this case, the multi-threaded model is more appropriate.

Public class MultiThreadApplication {public static void main (String [] args) {for (final String host: HttpConstant.HOSTS) {Thread t = new Thread (new Runnable () {public void run () {new SocketHttpClient (). Start (host, HttpConstant.PORT);}); t.start ();}

This approach may seem useful at first, but with a large amount of concurrency, the application will have a lot of threads. As you all know, on the server, each thread actually occupies a file handle. The number of handles on the server is limited, and a large number of threads, resulting in the consumption of switching between threads will be quite large. Therefore, this way must be unbearable in the scenario with large concurrency.

Multithreading + thread pool processing

Since there are too many threads, let's just control the number of threads created. Only a fixed number of threads are started for socket processing, which not only makes use of multi-thread processing, but also controls the resource consumption of the system.

Public class ThreadPoolApplication {public static void main (String [] args) {ExecutorService executorService = Executors.newFixedThreadPool (8); for (final String host: HttpConstant.HOSTS) {Thread t = new Thread (new Runnable () {public void run () {new SocketHttpClient (). Start (host, HttpConstant.PORT);}}) ExecutorService.submit (t); new SocketHttpClient () .start (host, HttpConstant.PORT);}}

With regard to the number of threads started, CPU-intensive is generally set at Number1 (N is the number of CPU cores), and IO-intensive is set at 2N + 1.

This way, it seems to be the best. Is it better if a thread can handle multiple socket connections at the same time without blocking each socket input and output data? This technique is called "IO multiplexing". The corresponding implementation is provided in the nio package of JAVA.

Supplement 1:TCP client and server public class TCP client {public static void main (String [] args) {new Thread (new Runnable () {@ Override public void run () {try {Socket s = new Socket ("127.0.0.1", 1234); / / build IO InputStream is = s.getInputStream (); OutputStream os = s.getOutputStream () BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (os)); / / send a message to the server bw.write ("Test client-server communication, the server receives the message and returns it to the client\ n"); bw.flush (); / / reads the message returned by the server BufferedReader br = new BufferedReader (new InputStreamReader (is)); String mess = br.readLine (); System._out_.println ("server:" + mess) } catch (UnknownHostException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();}) .start () }} public class TCP server {public static void main (String [] args) {new Thread (new Runnable () {@ Override public void run () {try {ServerSocket ss = new ServerSocket (1234); while (true) {System._out_.println ("start server...."); Socket s = ss.accept () System._out_.println ("client:" + s.getInetAddress (). GetLocalHost () + "connected to the server"); BufferedReader br = new BufferedReader (new InputStreamReader (s.getInputStream (); / / read the message sent by the client String mess = br.readLine (); System._out_.println ("client:" + mess); BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (s.getOutputStream (); bw.write (mess + "\ n") Bw.flush ();}} catch (IOException e) {e.printStackTrace ();}) .start () }} supplement 2:UDP client and server public class UDP client {public static void main (String [] args) {new Thread (new Runnable () {@ Override public void run () {byte [] arr = "Hello Server" .getBytes (); try {InetAddress inetAddress = InetAddress.getLocalHost (); DatagramSocket datagramSocket = new DatagramSocket () DatagramPacket datagramPacket = new DatagramPacket (arr, arr.length, inetAddress, 1234); datagramSocket.send (datagramPacket); System._out_.println ("send end");} catch (UnknownHostException e) {e.printStackTrace ();} catch (SocketException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace () }) .start ();}} public class UDP server {public static void main (String [] args) {new Thread (new Runnable () {@ Override public void run () {try {DatagramSocket datagramSocket = new DatagramSocket (1234); byte [] buffer = new byte [1024]; DatagramPacket packet = new DatagramPacket (buffer, buffer.length) DatagramSocket.receive (packet); System._out_.println ("server recv"); String msg = new String (packet.getData (), "utf-8"); System._out_.println (msg);} catch (SocketException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();}. Start () }} Thank you for reading, the above is the content of "how to use JAVA's socket". After the study of this article, I believe you have a deeper understanding of how to use JAVA's socket, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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