服务器端
import java.net.*;
import java.io.*;
public class QuoteServer {
static final int PORT = 6017;
private static final String[] fortunes = {
"真理惟一可靠的标准就是永远自相符合。 —— 欧文",
"土地是以它的肥沃和收获而被估价的;才能也是土地," +
"不过它生产的不是粮食,而是真理。如果只能滋生" +
"瞑想和幻想的话,即使再大的才能也只是砂地或盐池," +
"那上面连小草也长不出来的。 —— 别林斯基",
"我需要三件东西:爱情友谊和图书。然而这三者之间何其相通!" +
"炽热的爱情可以充实图书的内容,图书又是人们最忠实的" +
"朋友。 —— 蒙田",
"时间是一切财富中最宝贵的财富。 —— 德奥弗拉斯多",
"世界上一成不变的东西,只有“任何事物都是在不断变化的”这条真理。" +
" —— 斯里兰卡",
};
public static void main(String[] args ){
Socket client = null;
ServerSocket sock = null;
try {
sock = new ServerSocket(PORT);
//now listen for connection
while (true){
client = sock.accept();
//we have a connection
PrintWriter pout = new PrintWriter(client.getOutputStream(),true);
//write the Data to the socket
pout.println(fortunes[(int)(java.lang.Math.random() * fortunes.length)]);
pout.close();
client.close();
}
}
catch (IOException ioe){
System.err.println(ioe);
}
// finally {
// if(sock != null)
// sock.close();
// if(client != null)
// client.close();
// }
}
}
客户端:
import java.net.*;
import java.io.*;
public class QuoteClient
{
public static void main(String[] args) throws IOException {
InputStream in = null;
BufferedReader bin = null;
Socket sock = null;
try {
sock = new Socket("127.0.0.1",6017);
in = sock.getInputStream();
bin = new BufferedReader(new InputStreamReader(in));
String line;
while( (line = bin.readLine()) != null)
System.out.println(line);
}
catch (IOException ioe) {
System.err.println(ioe);
}
finally {
sock.close();
}
}
}