An example of a basic tutorial on Java network programming

  • 2020-04-01 03:28:27
  • OfStack

When we want to connect to the server over the network using TCP/IP in Java, we need to create a java.net.Socket object and connect to the server. If you want to use Java NIO, you can also create the SocketChannel object in Java NIO.

Create a Socket

The following example code is connected to port 80 on the server with IP address 78.64.84.171, which is our Web server (link: #), and port 80 is the Web service port.


Socket socket = new Socket("78.46.84.171", 80);

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

Socket socket = new Socket("jb51.net", 80);

Socket send data

To send data through the Socket, we need to get the OutputStream of the Socket. The sample code is as follows:


Socket socket = new Socket("jb51.net", 80);
OutputStream out = socket.getOutputStream(); out.write("some data".getBytes());
out.flush();
out.close(); socket.close();

The code is simple, but when you want to send data over the network to the server side, make sure you call the flush() method. The underlying TCP/IP implementation of the operating system first puts the data into a larger data cache block that is the size of the TCP/IP packet. The call flush() method simply writes the data to the operating system cache and does not guarantee that the data will be sent immediately.

Socket read data

To read data from the Socket, we need to get the Socket InputStream (InputStream), the code is as follows:


Socket socket = new Socket("jb51.net", 80);
InputStream in = socket.getInputStream(); int data = in.read();
//... read more data... in.close();
socket.close();

Code is not complicated, but it is important to note that the data read from the Socket of the input stream does not read a file that has been calls read () method until the return 1, because for the Socket, only when the server closes the connection, the Socket of the input stream will return 1, but in fact the server will not be kept close the connection. If we wanted to send multiple requests over a single connection, it would be foolish to close the connection in this case.

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

Close the Socket

After using the Socket, we must close the Socket and disconnect from the server. To close the Socket, just call the socket.close () method. The code is as follows:


Socket socket = new Socket("jb51.net", 80); socket.close();

(full text)


Related articles: