Java-- implement the TCP protocol Socket

TCP协议(Transmission Control Protocol)

Transmission Control Protocol (TCP, Transmission Control Protocol) is a connection-oriented, reliable, based on the byte stream transport layer communication protocol.
TCP is designed to adapt to support multi-network applications layered protocol hierarchy. Connected between the pair of host computers of different processes but interconnected computer communications networks rely on TCP provides reliable communication services. TCP assumes it can obtain a simple, potentially unreliable datagram service from the lower level protocols. In principle, TCP should be able to operate over a variety of communication systems connected to a packet switched from a hard-wired or circuit-switched network.

The reason why the reliable TCP protocol, because of the introduction of the three-way handshake mechanism and four waving.

  1. Before sending data to establish a connection, you need three-way handshake (in order to ensure the normal end can send and receive information).
  2. Normally transmit / receive data (in a byte stream).
  3. At the end of data transmission, it requires four wave (in order to ensure normal communication termination).

for example

For example:
Small A (transmission side)
small B (receiver)
three-way handshake:

  1. A: Are you there? -> A description can transmit data.
  2. B: I am. -> B to receive data and instructions can transmit data.
  3. A: I will nibbling chatter. -> Description A to receive data, can transmit data.

Three-way handshake connection is established, both ends demonstrate the ability of sending and receiving data, then you can transmit the useful data -> Create input and output streams through the socket object. Byte sent by the stream.
Four wave:

  1. A: I do not want to talk to you. -> A can send instructions.
  2. B may be prepared at this time is transmitted to the A, or A is receiving data. -> B can receive.
  3. B: Well, do not talk. -> B can transmit data.
  4. A B receives the message. -> A can receive data.

The underlying implementation, we can not touch, socket has helped us a good package, we just take it and use.

Java implementation

Client: client
server: server
to start the server, and then start the client, a successful connection is established, the server sends the data, and then the client receives the data.

Server implementation steps:

1. 've created a service ServerSocket provide a port number ---- ServerSocket

ServerSocket server = new ServerSocket(9999);

2. wait for Client Access - Client Access If the port number of the server, that means creation out of socket, three-way handshake to prove the connection is successful.

Socket socket = server.accept();

3. Get byte stream output in the form

OutputStream os = socket.getOutputStream();

4. The packed byte stream into a character stream

PrintWriter writer = new PrintWriter(os);

The character transmission data stream


TCPServer code implementation:

package server;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPServer {
    public static void main(String[] args) {
        try {
            System.out.println("====我是服务端===");
            //1.自己创建一个服务ServerSocket  提供一个端口号
            ServerSocket server = new ServerSocket(9999);
            //2.等待客户端访问
            Socket socket = server.accept();
            //socket创建出来,证明三次握手连接成功了
            //字节形式的输出流
            OutputStream os = socket.getOutputStream();
            //将字节流包装成字符流,为了发送我们的文字提供方便
            PrintWriter writer = new PrintWriter(os);
            System.out.println("连接成功,输入你想发送的话把:");
            Scanner input = new Scanner(System.in);
            String str = input.nextLine();
            writer.println(str);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The client implementation steps:

1. The client needs to take the initiative to create a connection, to the need to provide access to the server ip and port, create socket objects

Socket socket = new Socket("127.0.0.1",9999);

socket is created, proven three-way handshake is completed, you can connect it.
2. socket to create a stream of bytes

InputStream is = socket.getInputStream();

3. The packed byte stream into character stream (stream byte character conversion)

InputStreamReader isr = new InputStreamReader(is);

4. The read data


TCPClient code implementation:

package client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class TCPClient {
    public static void main(String[] args) {
        try {
            System.out.println("====我是客户端===");
            //1.客户端需要主动创建连接,去访问服务器  ip  port
            Socket socket = new Socket("127.0.0.1",9999);
            //socket创建完毕,证明三次握手完毕,可以连接啦
            //socket创建的字节流
            InputStream is = socket.getInputStream();
            //把字节流包装成字符流(字节字符转换流)
            InputStreamReader isr = new InputStreamReader(is);
            //由于这个isr对象不能读一行,所以我们再进行包装
            BufferedReader reader = new BufferedReader(isr);
            //reader可以读取一行
            String value = reader.readLine();
            System.out.println("客户端读到:"+value);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

test

Start the server, and then start the client.
Here Insert Picture Description

Published 46 original articles · won praise 15 · views 2614

Guess you like

Origin blog.csdn.net/qq_43598138/article/details/104407370