前言
socket底层、原理这些东西一搜一堆,这里就不重点说这些了
这里主要以代码形式大体说一下步骤过程,直接以注释的形式表现出来了
实现
主要过程:
启动服务端 > 启动客户端 > 客户端主动向服务端发送请求 > 服务端返回结果 > 客户端再次发送请求 > 服务端再次返回结果……
代码
服务端Server
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| import java.io.*; import java.net.*;
public class Server { public static void main(String args[]) { try{ ServerSocket server = null; try{ server = new ServerSocket(6666); }catch(Exception e){ e.printStackTrace(); } Socket socket=null; try{ socket=server.accept(); }catch(Exception e){ e.printStackTrace(); } BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter printWriter = new PrintWriter(socket.getOutputStream()); BufferedReader systemInBufferedReader = new BufferedReader(new InputStreamReader(System.in)); String systemIn; systemIn = systemInBufferedReader.readLine(); System.out.println("客户端Client:"+bufferedReader.readLine()); while(!systemIn.equals("bye")){ printWriter.println(systemIn); printWriter.flush(); System.out.println("Client:"+bufferedReader.readLine()); systemIn = systemInBufferedReader.readLine(); } printWriter.close(); bufferedReader.close(); socket.close(); server.close(); }catch(Exception e){ e.printStackTrace(); } } }
|
客户端Client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| import java.io.*; import java.net.*;
public class Client { public static void main(String[] args) { try{ Socket socket = new Socket("127.0.0.1",6666); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter printWriter = new PrintWriter(socket.getOutputStream()); BufferedReader systemInBufferedReader = new BufferedReader(new InputStreamReader(System.in)); String readline; readline = systemInBufferedReader.readLine(); while(!readline.equals("bye")){ printWriter.println(readline); printWriter.flush(); System.out.println("服务端Server:" + bufferedReader.readLine()); readline = systemInBufferedReader.readLine(); } printWriter.close(); bufferedReader.close(); socket.close(); }catch(Exception e){ e.printStackTrace(); } } }
|