需求:

  1. 模拟qq聊天功能:实现客户端与服务器(一对一)的聊天功能,客户端首先发起聊天,输入的内容在服务器端和客户端显示,然后服务器端也可以输入信息,同样信息在客户端和服务端显示。
  2. 提示:

    客户端

         1) 客户端编写聊天的方法chat()

         2) 要求使用BufferedReader与BufferedWriter缓冲类

         3) 编写用于测试的主方法调用chat()方法

    服务器端

         1) 编写提供服务的方法service()

         2) 编写用于测试的主方法调用service()方法

package Test1;

        import java.io.*;
        import java.net.Socket;

public class ChatClient {
    public void chat(){
        try {
            Socket s = new Socket("localhost", 10086);

            while (true){
                //获取输出流
                OutputStream outputStream = s.getOutputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                String line = br.readLine();

                outputStream.write(line.getBytes());

                //获取服务器的反馈
                InputStream inputStream = s.getInputStream();
                byte[] bytes = new byte[1024];
                int length  = inputStream.read(bytes);
                String string = new String(bytes, 0, length);
                System.out.println("服务器反馈:"+string);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args)throws IOException {
        new ChatClient().chat();
    }
}

 

package Test1;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class ChatServer {
    public void service(){
        try {
            ServerSocket ss = new ServerSocket(10086);

            Socket s = ss.accept();

            while (true){
                String ip = s.getInetAddress().getHostAddress();
                Date date = new Date();

                InputStream inputStream = s.getInputStream();
                byte[] bytes = new byte[1024];
                int length = inputStream.read(bytes);
                String s1 = new String(bytes, 0, length);
                System.out.println(ip+" "+date);
                System.out.println(s1);

                //给出反馈
                OutputStream outputStream = s.getOutputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                String line =br.readLine();

                outputStream.write(line.getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException{
        new ChatServer().service();
    }
}