This note wouldn’t tell you what is socket. I focus on write the programming steps.
Roughly saying, socket is an interface between application layer and TCP/IP.
You can think it as a control tools for TCP/IP.
Main API
- Socket class
public Socket(String host, int port) throws UnknownHostException, IOException
- getInputStream
Returns the input stream of Socket, and the user accepts the data from remote. - getOutputStream
Returns the output stream of Socket for sending data. - accept
public Socket accept() throws IOException
- Constructor
public ServerSocket(int port) throws IOException
Example:
Server side:
public class Server { public static void main(String[] args) throws IOException { //1. Create ServerSocket ServerSocket serverSocket = new ServerSocket(1234); //2. monitoring Socket socket = serverSocket.accept(); System.out.println("server start listen"); //3. input stream (send dy client) InputStream is = socket.getInputStream(); InputStreamReader reader = new InputStreamReader(is); BufferedReader br = new BufferedReader(reader); String content = null; // construct the sting buffers StringBuffer sb = new StringBuffer(); while ((content = br.readLine()) != null) { sb.append(content); } // 4. You can write your logic here to do //what you want those message do. System.out.println("server receiver: " + sb.toString()); // Output stream OutputStream os = socket.getOutputStream(); // Send data os.write("Server Hello".getBytes()); System.out.println("send message"); os.flush(); // 5. pause the monitor socket, then close related buffers socket.shutdownInput(); // Close output stream os.close(); // Close buffer reader br.close(); // Close stream reader reader.close(); // Close input stream is.close(); // Close monitor socket socket.close(); // Close server socket serverSocket.close(); } }
Client side:
public class Client{ //1. Create Client Socket socket = new Socket("your ip", 1234); //2. output stream OutputStream os = socket.getOutputStream(); //3. Send data os.write("Hello world".getBytes()); System.out.println("send message"); os.flush(); // 4. pause socket, then close related buffers socket.shutdownOutput(); os.close(); socket.close(); }
Ref.
https://hit-alibaba.github.io/interview/basic/network/Socket-Programming-Basic.html
https://programming.vip/docs/android-network-programming-socket.html