catalogue
1. TCP classes and common methods in socket
(1) ServerSocket class used by the server
2. Use ServerSocket to realize the interaction between a simple client segment and the server
II Initial knowledge of TCP Protocol segment
1. Understand TCP header structure
2. Three characteristics of TCP
I Use of TCP in socket API
1. TCP classes and common methods in socket
(1) ServerSocket class used by the server
Common methods are as follows:
Method name | Method description |
ServerSocket(int port) | Creates a server socket bound to the specified port |
ServerSocket(int port, int backlog) | Creates a server socket and binds it to the specified local port number, specifying the backlog. |
Socket accept() | Listen for the socket you want to connect to and accept it |
bind(SocketAddress endpoint) | Bind ServerSocket to a specific address (IP address and port number) |
InetAddress getInetAddress() | Returns the local address of this server socket |
void close() | Close this socket |
int getLocalPort() | Returns the port number on which this socket is listening |
Note: when using TCP protocol for transmission, it is transmitted as byte stream, so the problem of stream closing will be involved.
(2) socket class
Because accept() in serversocket is equivalent to taking a client request from the blocking queue. Therefore, you also need to use socket to cooperate.
Method name | Method description |
Socket(InetAddress address, int port) | Creates a stream socket and connects it to the specified port number of the specified IP address |
Socket(String host, int port) | Creates a stream socket and connects it to the specified port number on the specified host |
void bind(SocketAddress bindpoint) | Bind socket to local address |
void connect(SocketAddress endpoint) | Connect this socket to the server |
InetAddress getInetAddress() | Returns the address to which the socket is connected |
InputStream getInputStream() | Returns the input stream for this socket |
OutputStream getOutputStream() | Returns the output stream of this socket |
2. Use ServerSocket to realize the interaction between a simple client segment and the server
(1) Graphic thinking
(2) Code implementation
client
package javaweb.udptcp2.tcp; import java.io.*; import java.net.Socket; import java.util.Scanner; public class TCPClient { Socket socket = null; public TCPClient(String serverIp, int serverPort) throws IOException { socket = new Socket(serverIp,serverPort); } public void start() { System.out.println("Client run"); //Input request data through console Scanner sc = new Scanner(System.in); //Data is sent in byte stream, so stream is used for processing try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))){ while (true) { String request = sc.nextLine(); //Exit client if("exit".equals(request)) { break; } //Send the request to the server (receive the request in whatever format it is sent (line feed is included here, so you can use readLine to receive it)) bufferedWriter.write(request+"\n"); bufferedWriter.flush(); //Receive the response (this is where it is blocked while waiting for the response) String respons = bufferedReader.readLine(); //Output the response results to the console System.out.println(respons); } } catch (IOException e) { e.printStackTrace(); } } //Start client public static void main(String[] args) throws IOException { TCPClient client = new TCPClient("127.0.0.1", 9090); client.start(); } }
Server
package javaweb.udptcp2.tcp; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; //Realize the simple function of translating words public class TCPServer { ServerSocket serverSocket = null; HashMap<String, String> words = new HashMap<>(); public TCPServer(int port) throws IOException { serverSocket = new ServerSocket(port); words.put("cat","cat"); words.put("dog","dog"); words.put("fish","fish"); words.put("beef","beef"); } public void start() throws IOException { System.out.println("Server startup"); while (true) { //Remove a client connection from the blocking queue Socket clientSocket = serverSocket.accept(); //Here, another thread is used for data processing (to improve efficiency) Thread t = new Thread(new Runnable() { @Override public void run() { processConnection(clientSocket); } }); t.start(); } } private void processConnection(Socket clientSocket) { System.out.printf("[%s:%d] Client online\n",clientSocket.getInetAddress().toString(),clientSocket.getPort()); try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))){ while (true) { //Get request String request = bufferedReader.readLine(); //Calculate response based on request String respons = process(request); //Send response to clients bufferedWriter.write(respons+"\n"); //Using buffer requires refreshing the buffer bufferedWriter.flush(); System.out.printf("[%s:%d] request:%s;response:%s\n",clientSocket.getInetAddress().toString(),clientSocket.getPort(),request,respons); } } catch (IOException e) { System.out.printf("[%s:%d]Client offline\n",clientSocket.getInetAddress().toString(),clientSocket.getPort()); } } private String process(String request) { if(words.containsKey(request)) { return words.get(request); } return "Can't find"; } public static void main(String[] args) throws IOException { TCPServer server = new TCPServer(9090); server.start(); } }
(3) Operation results
II Initial knowledge of TCP Protocol segment
1. Understand TCP header structure
2. Three characteristics of TCP
- Connected: a connection needs to be established when transmitting data.
- Reliable transmission: there is confirmation response mechanism and retransmission mechanism; If the segment cannot be sent to the other party due to network failure, the TCP protocol layer will return an error message to the application layer.
- Byte oriented stream: network transmission of data according to bytes.