练习:创建一个多线程的TCP 服务器以及客户端

已知在服务器端的目录下有一个worldcup.txt,其格式如下:
2006/意大利
2002/巴西

该文件采用”年份/世界杯冠军 “的方式保存每一年世界杯冠军的信息。
要求从客户端输入年份,从服务器端查询,若查询到,返回举办地;反之,返回”未查询到该年份的世界杯举办地”。

class Client implements Runnable {
    private Socket s;
    private Scanner sc;
    {
        sc = new Scanner(System.in);
    }
    public void run() {
        s = new Socket();
        try {
            s.connect(new InetSocketAddress("localhost", 8090));
            String year = sc.nextLine();
            s.getOutputStream().write(year.getBytes());
            s.shutdownOutput();
            byte[] bs = new byte[1024];
            int len = s.getInputStream().read(bs);
            s.shutdownInput();
            System.out.println(new String(bs, 0, len));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class Server implements Runnable {
    private ServerSocket ss;
    private Map<String, String> map = new HashMap<>();
    {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("worldcup.txt"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                String[] strs = line.split("/");
                map.put(strs[0], strs[1]);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void run() {
        try {
            ss = new ServerSocket(8090);
            Socket s = ss.accept();
            byte[] bs = new byte[1024];
            int len = s.getInputStream().read(bs);
            s.shutdownInput();
            String year = new String(bs, 0, len);
            String dest = map.containsKey(year) ? map.get(year) : "未查询到该年份的世界杯举办地";
            s.getOutputStream().write(dest.getBytes());
            s.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Gavin_W_/article/details/82708961