1. TCP通信
1.1 一对一通信
服务端
package com.practice; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; /** * 服务端 * * @author yyx 2019年8月31日 */ public class TcpServer { public static void main(String[] args) { Socket socket = null; ServerSocket serverSocket = null; // 输入流 InputStream inputStream = null; // 输出流 OutputStream outputStream = null; try { serverSocket = new ServerSocket(8888); System.out.println("等待客户端连接!"); socket = serverSocket.accept(); inputStream = socket.getInputStream(); byte[] b = new byte[1024]; int len; while ((len = inputStream.read(b)) != -1) { String str = new String(b, 0, len); System.out.print(str); } outputStream = socket.getOutputStream(); outputStream.write("客户端您好,我是服务端".getBytes()); inputStream.close(); outputStream.close(); socket.close(); serverSocket.close(); } catch (Exception ex) { } } }
客户端
package com.practice; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; /** * 客户端 * * @author yyx 2019年8月31日 */ public class TcpClient { public static void main(String[] args) { Socket socket = null; InputStream inputStream = null; OutputStream outputStream = null; try { socket = new Socket("127.0.0.1", 8888); outputStream = socket.getOutputStream(); System.out.println("等待服务端回应"); outputStream.write("我是客户端,请多关照".getBytes()); // shutdownOutput():执行此方法,显式的告诉服务端发送完毕! socket.shutdownOutput(); System.out.println("**********************"); inputStream = socket.getInputStream(); byte[] b = new byte[1024]; int len; while ((len = inputStream.read(b)) != -1) { String str = new String(b, 0, len); System.out.print(str); } inputStream.close(); outputStream.close(); socket.close(); } catch (Exception ex) { } } }