使用IO和Socket服务在本地主机模拟文本转换服务器.
需求分析:从客户端发送文本数据到服务器端,服务器端将文本数据转换为大写后返回给客户端,而且客户端可以不断的输入进行文本转换,当客户端输入over时,转换结束.
客户端:键盘录入,网络输出流和读取服务器返回的输入流
1.建立服务
2.获取键盘录入
3.将数据发送给服务端
4.获取服务器端返回的转换数据
5.结束,关闭资源.
->创建Socket服务,并指定要连接的主机和端口
- class Client
- {
- public static void main(String[] args) throws Exception
- {
- Socket s = new Socket("localhost", 10000);
- BufferedReader bufr =
- new BufferedReader(new InputStreamReader(System.in));
- BufferedWriter bufOut =
- new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
- BufferedReader bufIn =
- new BufferedReader(new InputStreamReader(s.getInputStream()));
- String line = null;
- while((line = bufr.readLine()) != null)
- {
- if("over".equals(line))
- break;
- bufOut.write(line);
- String str = bufIn.readLine();
- System.out.println("Server: " + str);
- }
- bufr.close();
- s.close();
- }
- }
class Client { public static void main(String[] args) throws Exception { Socket s = new Socket("localhost", 10000); BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufOut = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); String line = null; while((line = bufr.readLine()) != null) { if("over".equals(line)) break; bufOut.write(line); String str = bufIn.readLine(); System.out.println("Server: " + str); } bufr.close(); s.close(); } }
服务器:socket读取流和socket输出流
->建立服务端的socket服务,SocketServer并监听一个端口
->通过SocketServer的方法accept,获取客户端对象.
- class Server
- {
- public static void main(String[] args) throws Exception
- {
- ServerSocket ss = new ServerSocket(10000);
- Socket s = ss.accept();
- String ip = s.getInetAddress().getHostAddress();
- System.out.println(ip + ":" + " is connected");
- BufferedReader bufIn =
- new BufferedReader(new InputStreamReader(s.getInputStream()));
- BufferedWriter bufOut =
- new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
- String line = null;
- while((line = bufIn.readLine()) != null)
- {
- System.out.println(line);
- bufOut.write(line.toUpperCase());
- }
- s.close();
- ss.close();
- }
- }