Jane said

If you want to use TCP/IP in Java to connect to the server over the network, you need to create a java.net.Socket object to connect to the server. If you use JavaNIO, you can also create SocketChannel objects in JavaNIO.

Step 1 Create the Socket

The following sample code connects to port 80 on the server at IP address 89.53.64.191. This server is a Web server, and port 80 is a Web service port.

Socket socket = new Socket("89.53.64.191".80);

Copy the code

We can also use domain names instead of IP addresses as in the following example:

Socket socket = new Socket("wyzhang.com".80);

Copy the code

Step 2 The Socket sends data

Send data through the Socket to obtain the Socket OutputStream, the following code example:

Socket socket = new Socket("jenkov.com".80);

OutputStream out = socket.getOutputStream(); 



out.write("some data".getBytes());

out.flush();

out.close(); 



socket.close();

Copy the code

The code is very simple, but to send data to the server over the network, be sure to call flush(). The underlying TCP/IP implementation of the operating system first puts data into a larger data cache block that is appropriate to the size of the TCP/IP packet.

Step 3 The Socket reads the data

To read data from a Socket, we need to get the Socket’s InputStream, which looks like this:

Socket socket = new Socket("jenkov.com".80);

InputStream in = socket.getInputStream(); 



int data = in.read();

/ /... read more data...



in.close();

socket.close();

Copy the code

The code is not too complicated, but it is important to note that reading data from the Socket’s input stream does not work like reading a file and calling the read() method until it returns -1, because the Socket’s input stream returns -1 only when the server closes the connection. It’s the fact that the server doesn’t keep closing connections. Let’s say we want to send multiple requests over a single connection, and it would be foolish to close the connection in this case.

Therefore, when reading data from the Socket input stream, we must know the number of bytes to read. This can be done by asking the server to tell us in the data how many bytes were sent, or by setting special character markers at the end of the data.

Finally close the Socket

After using the Socket, we must close the Socket and disconnect it from the server. To close the Socket, just call socket.close (), which looks like this:

Socket socket = new Socket("jenkov.com".80); 



socket.close();

Copy the code

conclusion

Socket is actually so, write good input flow output flow, there is no problem, if there are students who want to learn programming can reply “learning” to receive a line of big factory Java interview summary + Alibaba Taishan manual + knowledge learning thinking guide + a 300 page PDF document Java core knowledge summary!

I wish the students progress in their studies!