服务器端: import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket;
public class SocketServerTest { String[] dateString = { "d", "c", "3", "4", "=" };
public static void main(String[] args) { SocketServerTest socketClient = new SocketServerTest(); socketClient.startTest();}public void startTest() { try { ServerSocket serverSocket = new ServerSocket(3989);// get port while (true) {// server will start all the time Socket socket = serverSocket.accept();// create socket PrintWriter printWriter = new PrintWriter( socket.getOutputStream());// create // printwriter printWriter.print(getData());// out print data printWriter.close(); printWriter.print(getData());// out print data } } catch (Exception e) { e.printStackTrace(); }}public String getData() { int radom = (int) (Math.random() * dateString.length); return dateString[radom];}
}
客户端代码: import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.Socket;
public class SocketClientTest { public static void main(String[] args) { SocketClientTest socketClientTest = new SocketClientTest(); for (int i = 0; i <= 10; i++) { socketClientTest.start(); }
}public void start() { try { Socket socket = new Socket("127.0.0.1", 3789);// get port InputStreamReader inputStreamReader = new InputStreamReader( socket.getInputStream());// get inputstream BufferedReader reader = new BufferedReader(inputStreamReader);// bufferedReader String dataString = reader.readLine(); System.out.println(dataString); reader.close(); } catch (Exception e) { e.printStackTrace(); }}
}