1. TCP communication
1.1-one communication
Server
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; // output stream the OutputStream the outputStream = null ; the try { serverSocket = new new the ServerSocket (8888 ); System.out.println ( "connection requests from clients!" ); Socket = serverSocket.accept (); inputStream = Socket.getInputStream (); byte [] B = new new byte [1024 ]; int len; the while (! (len = InputStream.read (B)) = -1 ) { String STR = new 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) { } } }
Client
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 new the Socket ( "127.0.0.1", 8888 ); outputStream = Socket.getOutputStream (); System.out.println ( "wait for the server to respond" ); OutputStream.write ( "I am a client thanking you in advance" .getBytes ()); // shutdownOutput (): perform this method, explicitly tell the server sends finished! socket.shutdownOutput (); System.out.println ( "************************************************************" ); inputStream = Socket.getInputStream (); byte [] B = new new byte [1024 ]; int len; the 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) { } } }