服务端:
package com.socket.tcp; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; /** * 基于TCP协议通信,服务端 */ public class Server { public static void main(String[] args) { ServerSocket serverSocket = null; Socket socket = null; BufferedReader in = null; PrintWriter out = null; try { serverSocket = new ServerSocket(10000); socket = serverSocket.accept(); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream()); while (true) { String str = in.readLine(); System.out.println("来自客户端的:" + str); out.println("服务端收到了来自客户端的:" + str); out.flush(); if ("end".equals(str)) { break; } } } catch (Exception e) { e.printStackTrace(); } finally { try { in.close(); out.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } } }
客户端:
package com.socket.tcp; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class Client { /** * 基于TCP协议通信,客户端 */ public static void main(String[] args) { Socket socket = null; BufferedReader in = null; PrintWriter out = null; BufferedReader wt = null; try { socket = new Socket("127.0.0.1", 10000);//InetAddress.getLocalHost() in = new BufferedReader(new InputStreamReader(socket.getInputStream()));//收到的内容 wt = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(socket.getOutputStream());//获取输出流,发送的 while (true) { String str = wt.readLine(); out.println(str); out.flush(); if ("end".equals(str)) { break; } System.out.println(in.readLine());//收到的 } } catch (Exception e) { e.printStackTrace(); } finally { try { in.close(); out.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } } }