package com.batman.eureka; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.Socket; import java.util.Scanner; public class HClient { static int i = 0; public static void main(String[] args) { while (true) { try { Socket socket = new Socket("127.0.0.1", 1234); /* System.out.println("please input..."); Scanner scanner = new Scanner(System.in); String p = scanner.nextLine(); if (p.equals("bye")) { socket.close(); break; }*/ String p = "my client"; i = i + 1; if(i == 51) break; // 发送给服务器的数据 DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.writeUTF(p + " " + i); // 接收服务器的返回数据 /* DataInputStream in = new DataInputStream(socket.getInputStream()); System.out.println("hserver:" + in.readUTF());*/ socket.close(); } catch (Exception e) { e.printStackTrace(); } } } }
package com.batman.eureka; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class HServerApp implements Runnable { public int port; // ExecutorService executorService = Executors.newCachedThreadPool(); ExecutorService executorService = Executors.newFixedThreadPool(5); public HServerApp(int port) { this.port = port; } @Override public void run() { try { ServerSocket server = new ServerSocket(port); while (true) { //等待client的请求 // System.out.println("waiting..."); Socket socket = server.accept(); // 接收客户端的数据 DataInputStream in = new DataInputStream(socket.getInputStream()); String str = in.readUTF(); //socket.close(); /* try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ System.out.println("client:" + str); executorService.execute(new TestRunnable()); // 发送给客户端数据 /* DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.writeUTF("hi,i am hserver!i say:" + str);*/ } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { HServerApp serverApp = new HServerApp(1234); serverApp.run(); } } class TestRunnable implements Runnable{ public void run(){ System.out.println(Thread.currentThread().getName() + "线程被调用了。"); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }