When we want to connect to a 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 a SocketChannel object in Java NIO.
Create Socket
The following sample code is connected to port 80 on the server with the IP address 78.64.84.171. This server is our Web server (www.VeVB.COm), and port 80 is the Web service port.
Copy the code code as follows:
Socket socket = new Socket("78.46.84.171", 80);
We can also use domain names instead of IP addresses as in the following example:
Copy the code code as follows:
Socket socket = new Socket("VeVB.COm", 80);
Socket sends data
To send data through Socket, we need to obtain the Socket's output stream (OutputStream). The sample code is as follows:
Copy the code code as follows:
Socket socket = new Socket("VeVB.COm", 80);
OutputStream out = socket.getOutputStream();
out.write("some data".getBytes());
out.flush();
out.close();
socket.close();
The code is very simple, but if you want to send data to the server through the network, you must not forget to call the flush() method. The underlying TCP/IP implementation of the operating system will first put the data into a larger data cache block, and the size of the cache block is adapted to the TCP/IP packet size. (Translator's Note: Calling the flush() method only writes data to the operating system cache and does not guarantee that the data will be sent immediately)
Socket reads data
To read data from the Socket, we need to obtain the Socket's input stream (InputStream). The code is as follows:
Copy the code code as follows:
Socket socket = new Socket("VeVB.COm", 80);
InputStream in = socket.getInputStream();
int data = in.read();
//... read more data...
in.close();
socket.close();
The code is not complicated, but it should be noted that reading data from the input stream of the Socket does not read the file. The read() method is called until -1 is returned, because for the Socket, only when the server When the connection is closed, the Socket's input stream will return -1, but in fact the server does not keep closing the connection. Suppose we want to send multiple requests over a single connection, then closing the connection in this case would be silly.
Therefore, when reading data from the Socket input stream, we must know the number of bytes to be read. This can be achieved by letting the server tell the data how many bytes were sent, or by setting special characters at the end of the data. The markup method is implemented.
Close Socket
After using the Socket, we must close the Socket and disconnect from the server. To close a Socket, you only need to call the Socket.close() method. The code is as follows:
Copy the code code as follows:
Socket socket = new Socket("VeVB.COm", 80);
socket.close();
(Full text ends)