package cn.example.socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; public class MyClient { public static void main(String[] args) throws UnknownHostException, IOException { // 定义socket Socket socket = new Socket("localhost", 9999); // 获取输入输出 InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); // 处理 PrintWriter pw = new PrintWriter(outputStream); pw.print("hello " + "socket ");//换行符 pw.flush(); //pw.close();//不能关闭 Exception in thread "main" java.net.SocketException: socket closed String result = new BufferedReader(new InputStreamReader(inputStream)) .readLine(); System.out.println(result); inputStream.close(); outputStream.close(); } }
package cn.example.socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; public class MyServer { public static void main(String[] args) throws IOException { //建立server ServerSocket serverSocket = new ServerSocket(); //绑定Ip serverSocket.bind(new InetSocketAddress("localhost", 9999)); //启用一个线程处理 while(true){ System.out.println("server start"); new Thread(new MysocketThread(serverSocket.accept())).start(); } } } class MysocketThread implements Runnable { private Socket socket; InputStream inputStream = null; OutputStream outputStream = null; public MysocketThread(Socket socket) { super(); this.socket = socket; } @Override public void run() { try { //定义输入输出流 inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); //解析读入数据 BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String param = br.readLine(); //根据读入的数据处理业务逻辑,然后返回,这里简单返回 String backValue = "ok "+param+" "; PrintWriter pw = new PrintWriter(outputStream); pw.print(backValue); pw.flush(); pw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { outputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }