/**10 、使用 TCP 协议完成一个客户端一个服务器。客户端从键盘输入读取一个字符串,发送到服务器。
服务器接收客户端发送的字符串,反转之后发回客户端。客户端接收并打印。
* 客户端 */
import java.io.*;
import java.net.*;
public class Test10_Client {
public static void main(String[] args) throws Exception {
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();
Stringstr=bufIn.readLine();
System. out .print( "server:" +str);
}
s.close();
}
}
/** 服务器端
*/ import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter ;
import java.net.ServerSocket;
import java.net.Socket;
public class Test10_Server {
public static void main(String []agrs) throws Exception
{
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); // 字符串反转处理
Stringstr=re.reverse().toString();
System. out .println(re+ "++ ++" +str); // 服务器本地输出
bufout.write(str); // 将字符反转并输出到客户端
bufout.newLine();
bufout.flush();
}
s.close();
}
}
|