操作系统概念 第三章 编程题 3.16

服务器端

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();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值