本帖最后由 途中ms前进 于 2015-5-25 21:10 编辑
0、使用TCP协议完成一个客户端一个服务器。客户端从键盘输入读取一个字符串,发送到服务器。
//服务器接收客户端发送的字符串,反转之后发回客户端。客户端接收并打印。
import java.io.*;
import java.net.*;
class TCPClint
{public static void main(String[] args) throws Exception
{Socket s=new Socket("192.168.1.101",10009);
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader bufr1=new BufferedReader(new InputStreamReader(s.getInputStream()));
String line=null;
while((line=bufr.readLine())!=null)
{if("over".equals(line))
break;
bufw.write(line);
bufw.flush();
bufw.newLine();
String str=bufr1.readLine();
System.out.println(str);
}
s.close();
bufr.close();
}
}
class Server
{public static void main(String[] args) throws Exception
{ServerSocket ss=new ServerSocket(10009);
Socket s=ss.accept();
String ip=ss.getInetAddress().getHostAddress();
System.out.println(ip+"...connected");
BufferedReader bufr=new BufferedReader(new InputStreamReader(ss.getInputStream()));
BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(ss.getOutputStream()));
String line=null;
while((line=bufr.readLine())!=null)
{char[] chs=line.toCharArray();
String s=new String(reverse(chs));
bufw.write(s);
bufw.newLine();
bufw.flush()
}
s.close();
ss.close();
}
public static void reverse(char[] arr)
{for(int start=0,end=arr.length-1;start<end;start++,end--)
swap(arr,start,end);
}
public static void swap(char[] arr,int x,int y)
{char temp=arr[x];
arr[x]=arr[y];
arr[y]=temp;
}
}
|
|