java socket demo
//TCPServer.java package msb.demo.socket; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Date; public class TCPServer { /** * @param args * @throws IOException * @throws InterruptedException */ public static void main(String[] args) throws IOException, InterruptedException { ServerSocket serverSocket = new ServerSocket(3333); while (true) { Socket socket = serverSocket.accept(); Thread.sleep(2000); //read from client DataInputStream dis = new DataInputStream(socket.getInputStream()); String data = dis.readUTF(); String msg =(new Date() + " accept:" + data); System.out.println("Server received:"+msg); //write to client DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeUTF(msg); dis.close(); dos.close(); socket.close(); } } } //TCPClient.java package msb.demo.socket; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; public class TCPClient { static int cnt = 0; /** * @param args * @throws IOException * @throws UnknownHostException */ public static void main(String[] args) throws Exception { for(int i=0;i<5;i++) connectServer(); } static void connectServer() throws Exception{ Socket socket = new Socket("127.0.0.1",3333); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); //write to server dos.writeUTF("p"+ (++cnt)); dos.flush(); //read from server DataInputStream dis = new DataInputStream(socket.getInputStream()); String msg = dis.readUTF(); System.out.println("Client received:"+msg); dos.close(); dis.close(); socket.close(); } }