ii- /*
- TCP练习:客户机控制台发送数据,服务器返回大写
- */
- import java.io.*;
- import java.net.*;
- class ClientDemo2
- {
- public static void main(String[] args) throws Exception
- {
- Socket s = new Socket("192.168.31.1",10003);
- //输出流和输入流
- OutputStream out = s.getOutputStream();
- InputStream in = s.getInputStream();
- //控制台输入
- BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));//控制台输入
- BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(out));//输出
- BufferedReader bufin = new BufferedReader(new InputStreamReader(in));//接收服务器信息
-
- System.out.println("客户端启动。。。");
- //发送输入的字符
- String line = null;
- while((line=bufr.readLine())!=null)//readLine()不返回分行符,需要重新添加
- {
- if("over".equals(line))
- break;
- bufw.write(line);
- bufw.newLine();
- bufw.flush();
-
- System.out.println("客户端发送消息。。。");
- //接收回来的字符
- String msg = bufin.readLine();
- System.out.println(msg);
- }
- s.close();
- bufr.close();
- }
- }
- class ServerDemo2
- {
- public static void main(String[] a) throws Exception
- {
- ServerSocket ss = new ServerSocket(10003);
- Socket s = ss.accept();
- InputStream ins = s.getInputStream();
- OutputStream outs = s.getOutputStream();
- //客户机信息
- String ip = s.getInetAddress().getHostAddress();
- String name = s.getInetAddress().getHostName();
-
- //读取客户端发来的信息
- BufferedReader bufins = new BufferedReader(new InputStreamReader(ins));
- BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(outs));
- String line = null;
- System.out.println("服务器启动。。。");
- while((line = bufins.readLine())!=null)
- {
- System.out.println(line);
- bufw.write((line.toUpperCase()));
- bufw.newLine();
- bufw.flush();
- }
- s.close();
- ss.close();
- }
- }
复制代码
|
|