本帖最后由 上官睿鹏 于 2014-3-12 16:53 编辑
这应该是黑马基础测试题里面的吧?我记得之前做过~客户端:
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.net.Socket;
- import java.util.Scanner;
- public class Client {
- public static void main(String[] args) {
- launchClient();
- }
- private static void launchClient() {
- Socket s = null;
- DataOutputStream dos = null;
- DataInputStream dis = null;
- Scanner sc = null;
-
- try {
- while(true) {
- s = new Socket("127.0.0.1", 9999); //创建请求指定服务器的Socket对象
- dos = new DataOutputStream(s.getOutputStream()); //创建数据输出流
-
- System.out.println("请输入:");
- sc = new Scanner(System.in);
- String str = sc.next(); //得到键盘输入的数据
- dos.writeUTF(str); //将数据写入
-
- dis = new DataInputStream(s.getInputStream());//创建输入流
- System.out.println("反转之后:" + dis.readUTF()); //接受并打印经服务器反转之后的字符串
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- dos.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- sc.close();
-
- try {
- s.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
复制代码
服务器端:
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class Server {
- public static void main(String[] args) {
- launchServer();
- }
- private static void launchServer() {
- ServerSocket server = null;
- Socket s = null;
- DataInputStream dis = null;
- DataOutputStream dos = null;
- while(true) {
- try {
- server = new ServerSocket(9999); //创建绑定端口9999的ServerSocket对象
-
- System.out.println("服务器已启动!");
-
- s = server.accept(); //接收客户端请求,得到Socket
- dis = new DataInputStream(s.getInputStream()); //创建数据输入流
- String m = dis.readUTF(); //读取客户端发送的数据并返回一个String类型的对象
-
- StringBuffer sb = new StringBuffer(m); //将String类型转换成StringBuffer类型便已反转
- m = sb.reverse().toString(); //将从客服端接受的字符串反转
-
- dos = new DataOutputStream(s.getOutputStream()); //穿件数据输出流
- dos.writeUTF(m); //将反转之后的字符串写入内存让客户端读取
-
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- dis.close();
- s.close();
- server.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- }
- }
- }
复制代码
|