发表3 分钟读完 (大约441个字)
简单Socket服务器实现
简单Socket服务器实现
服务端
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 65 66 67 68 69 70 71 72 73
|
public class TestServer {
public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(8989); ExecutorService executorService = Executors.newCachedThreadPool();
while (true) { Socket socket = server.accept(); Task task = new Task(socket); executorService.execute(task); } } }
class Task implements Runnable { Socket socket;
public Task(Socket socket) { this.socket = socket; }
@Override public void run() { try { InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream();
InputStreamReader isr = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(isr);
String str; PrintStream ps = new PrintStream(outputStream); while ((str = bufferedReader.readLine()) != null) { System.out.println(Thread.currentThread().getName() + ": tick,tick,tick..."); if ("bye".equals(str)) { ps.println("see you"); break; }
StringBuilder sb = new StringBuilder(str); sb.reverse();
ps.println(sb.toString()); } } catch (Exception e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
|
客户端
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
|
public class TestClient { public static void main(String[] args) throws IOException { Socket socket = new Socket("192.168.124.17", 8989);
Scanner scanner = new Scanner(System.in); PrintStream ps = new PrintStream(socket.getOutputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) { System.out.println("Please print something:"); String word = scanner.nextLine();
ps.println(word);
String result = br.readLine(); System.out.println("Lucy: " + result); if ("see you".equals(result)) { break; } }
scanner.close(); socket.close(); } }
|