客户端:
package com.itheima;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class Test10 {
/**
**/
//客户端
public static void main(String[] args)throws Exception {
System.out.println("启动客户端............");
Socket s = new Socket("192.168.0.103", 8080);//创建Socket对象;
//从键盘获取输入流到缓冲区;
BufferedReader buf = 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 = buf.readLine()) !=null) {
if ("over".equals(line))
break;
bufout.write(line);
bufout.newLine();
bufout.flush();
String str=bufIn.readLine();
System.out.print("server:"+str);
}
s.close();
}
}
服务端:
package com.itheima;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Test10Server {
public static void main(String []agrs)throws Exception{
System.out.println("启动服务器端............");
// 创建服务端ServerSocket
ServerSocket ss=new ServerSocket(8080);
//获取客户端对象
Socket s= ss.accept();
String ip=s.getInetAddress().getHostAddress();
System.out.println(ip+"we are connected!");
BufferedReader buf =new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter bufout=new BufferedWriter(new OutputStreamWriter(s.getOutputStream())
);//创建一个输出流
// bufout.write(ip+"we are connected!");
String line=null;
while((line=buf.readLine())!=null){
System.out.println(line);
StringBuffer re=new StringBuffer(line);//字符串反转处理
String str=re.reverse().toString();
System.out.println(re+"++ ++"+str);//服务器本地输出
bufout.write(str);//将字符反转并输出到客户端
bufout.newLine();
bufout.flush();
}
s.close();
}
}
|
|