TCP通信

TCP通信

image-20200513180545649

TCP通信:面向连接的通信,客户端和服务器端必须经过3次握手,建立逻辑连接,才能通信(安全)

通信步骤:

服务器端先启动,服务器端不会主动的请求客户端,必须使用客户端请求服务器端,客户端和服务器端就会建立一个逻辑连接,而这个连接中包含一个对象,这个对象就是IO对象,客户端与服务器端就可以使用IO对象进行通信,通信的数据不仅仅是字符,所以IO对象是字节流对象

image-20200513182428665

Socket

  • public class Socket
    extends Object
    implements Closeable

    该类实现客户端套接字(也称为“套接字”)。套接字是两台机器之间通讯的端点。

    套接字的实际工作由SocketImpl类的实例执行。 应用程序通过更改创建套接字实现的套接字工厂,可以配置自己创建适合本地防火墙的套接字。

  • Socket(String host, int port) 创建流套接字并将其连接到指定主机上的指定端口号。

    参数 :

    host - 主机名,或 null的环回地址。

    port - 端口号。

成员方法:

OutputStream getOutputStream() 返回此套接字的输出流。

InputStream getInputStream() 返回此套接字的输入流。 image-20200513185249058

image-20200513190933490

public class TCPServer {
  public static void main(String[] args) {
      ServerSocket serverSocket = null;
      try {
          serverSocket = new ServerSocket(8888);
          Socket socket = serverSocket.accept();
          InputStream inputStream = socket.getInputStream();
          byte[] bytes = new byte[1024];
          int len = inputStream.read(bytes);
          System.out.println(new String(bytes,0,len));
          OutputStream outputStream = socket.getOutputStream();
          outputStream.write("收到谢谢".getBytes());
          socket.close();
          serverSocket.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
  }
}
public class TCPClient {
  public static void main(String[] args) {
      Socket socket = null;
      try {
          socket = new Socket("127.0.0.1", 8888);
          OutputStream outputStream = socket.getOutputStream();
          outputStream.write("你好服务器".getBytes());
          InputStream inputStream = socket.getInputStream();
          byte[] bytes = new byte[1024];
          int len = inputStream.read(bytes);
          System.out.println(new String(bytes,0,len));
      } catch (IOException e) {
          e.printStackTrace();
      }finally {
          try {
              socket.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  }
}

 

原文地址:https://www.cnblogs.com/lxy522/p/12885276.html