您的位置:首页 > 理论基础 > 计算机网络

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

2018-09-14 21:32 281 查看

已知在服务器端的目录下有一个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();
}
}
}
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐