/**
* 第10题:使用TCP协议完成一个客户端一个服务器。客户端从键盘输入读取一个字符串,发送到服务器。
* 服务器接收客户端发送的字符串,反转之后发回客户端。客户端接收并打印。
* @author 刘德旺
*/
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
class Test10Client
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("192.168.1.1",58239);
//定义读取键盘数据流对象
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//定义目的,将数据写入到socket输入流中,发送给服务端
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//定义一个socket读取流,读取服务器返回的信息
BufferedReader brIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
String line=null;
while((line=br.readLine())!=null)
{
//结束字符
if("exit".equals(line))
break;
bw.write(line);
bw.newLine();
bw.flush();
String str=brIn.readLine();
System.out.println("服务端:"+str);
}
br.close();
s.close();
}
}
class Test10Server {
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(58239);
Socket s = ss.accept();
System.out.println("与IP地址为:"+s.getInetAddress().getHostAddress()+"连接成功!");
//读取socket流中的数据
BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
//socket输出流
BufferedWriter bufOut=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String line=null;
while((line=bufIn.readLine())!=null)
{
System.out.println("客户端:"+line);
bufOut.write(new StringBuilder(line).reverse().toString());
bufOut.newLine();
bufOut.flush();
}
s.close();
ss.close();
}
}
|
|