服务端: package com.batch.service.impl; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class serverSoecktMain { public static void main(String[] args) { ServerSocket server = null; Socket socket = null; BufferedReader br = null; PrintWriter pr =null; try { try { server = new ServerSocket(6666); } catch (Exception e) { System.out.println("can not listen to:" + e); } System.out.println("server------------------------------"); try { socket = server.accept(); } catch (Exception e) { System.out.println("Error." + e); } br= new BufferedReader(new InputStreamReader(socket.getInputStream())); pr= new PrintWriter(socket.getOutputStream()); pr.println("服务端:this is a server"); pr.flush(); System.out.println("Client:" + br.readLine()); } catch (Exception e) { System.out.println("Error:" + e); } finally{ try { server.close(); socket.close(); br.close(); pr.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } 客户端: package com.batch.service.impl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; public class serverMain { public static void main(String[] args) { Socket socket= null; PrintWriter pr= null; BufferedReader br = null; try { socket = new Socket("127.0.0.1",6666); pr = new PrintWriter(socket.getOutputStream()); br = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println("Client------------------------------"); pr.println("client is good!"); pr.flush(); System.out.println("Server:" + br.readLine()); } catch (Exception e) { System.out.println("Error" + e); //错则打印错信息 } finally{ try { socket.close(); pr.close(); br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }