Server.java
Import java.io.*; import Java.net.*; public classServer { public Static voidmain (string args[]) {string [] Answer={"South Africa","into the world Cup.","haha ... That's a funny question!"}; ServerSocket serverforclient=NULL; Socket Socketonserver=NULL; DataOutputStream out=NULL; DataInputStreaminch=NULL; Try{serverforclient =NewServerSocket ( .); } Catch(ioexception e1) {System. out. println (e1); } Try{System. out. println ("waiting for customer to call"); Socketonserver= Serverforclient.accept ();//blocked status, unless a customer calls out=NewDataOutputStream (socketonserver.getoutputstream ()); inch=NewDataInputStream (socketonserver.getinputstream ()); for(intI=0; i<answer.length;i++) {String s=inch. readUTF ();//in Reading information, blocking stateSystem. out. println ("the server receives the Customer's question:"+s); out. writeUTF (answer[i]); Thread.Sleep ( -); } } Catch(Exception E) {System. out. println ("Customer is disconnected"+e); } }}
Client.java
Import java.io.*; import Java.net.*; public classClient { public Static voidmain (string args[]) {string [] mess={"where is the 2010 World Cup held?","did Brazil enter the world cup?","China entering the world cup?"}; Socket mysocket; DataInputStreaminch=NULL; DataOutputStream out=NULL; Try{mysocket=NewSocket ("127.0.0.1", .); inch=NewDataInputStream (mysocket.getinputstream ()); out=NewDataOutputStream (mysocket.getoutputstream ()); for(intI=0; i<mess.length;i++) { out. writeUTF (mess[i]); String s=inch. readUTF ();//in Reading information, blocking stateSystem. out. println ("the customer receives a response from the Server:"+s); Thread.Sleep ( -); } } Catch(Exception E) {System. out. println ("Server is disconnected"+e); } } }
Java Network programming socket programming