练习:创建一个多线程的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(); } } }阅读更多
相关文章推荐
- Java基础知识强化之网络编程笔记14:TCP之多个客户端上传到一个服务器的思考(多线程改进)
- python3+PyQt5 创建多线程网络应用-TCP客户端和TCP服务器
- 自己学习android网络应用部分,练习的一个多线程的服务器和客户端
- 关于socket应用:一个不断监听一个进程的服务器以及发送信息的客户端 TCP的三次握手和四次挥手
- TCP/TP编程 - 一个简单的Linux下C写的socket服务器客户端程序
- tcp和udp多线程的epoll服务器+客户端源代码
- 基于linux poll模型的tcp服务器------一个服务器如何与多个客户端进行通信?
- nodejs中一个简单的TCP服务器端和客户端的聊天服务器
- 用Python实现一个简单的多线程TCP服务器的教程
- NodeJS 创建TCP服务器 客户端
- Winsock程序设计入门(3)修订版-多线程TCP服务器和客户端
- 当你在浏览器输入一个网址,如http://www.taobao.com,按回车之后发生了什么?请从技术的角度描述,如浏览器、网络(UDP、TCP、HTTP等),以及服务器等各种参与对象上由此引发的一系
- {网络编程}和{多线程}应用:基于TCP协议【实现多个客户端发送文件给一个服务器端】--练习
- tcp和udp多线程的epoll服务器+客户端源代码
- 创建WebService服务器以及客户端调用
- node.js中net模块创建服务器和客户端(TCP)
- tcp和udp多线程的epoll服务器+客户端源代码
- java Socket--tcp 一个服务器多客户端
- 笔试题14:用TCP通信模型创建一个Web服务器(源码)
- 一个简单的基于node.js的TCP服务器和基于C++的TCP客户端通信示例程序