BO

java代码实现聊天功能-网络通信
今天学习网络通信,一个很有意思的小案例。服务器端public static void main(String[] ...
扫描右侧二维码阅读全文
28
2019/03

java代码实现聊天功能-网络通信

Ad6MkQ.png

今天学习网络通信,一个很有意思的小案例。

服务器端

public static void main(String[] args) throws IOException {
        //启动占用端口
        ServerSocket ser = new ServerSocket(8888);
        //等待客户连接
        Socket socket = ser.accept();
        //创建流
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintStream ps = new PrintStream(socket.getOutputStream());
        //键盘录入
        Scanner sc = new Scanner(System.in);
        //开启多线程
        new Thread(){
            @Override
            public void run() {
               while(true){
                   try {
                       String s = br.readLine();
                       System.out.println(new Date(System.currentTimeMillis())+":"+s);
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
               }
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
              while(true){
                  String s = sc.nextLine();
                  System.out.print(new Date(System.currentTimeMillis())+":"+s);
				  ps.println(s);
              }
            }
        }.start();

客户端

public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",8888);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
Scanner sc = new Scanner(System.in);
new Thread(){
@Override
public void run() {
	while(true){
		String s = sc.nextLine();
		System.out.println(new Date(System.currentTimeMillis())+":"+s);
		ps.println(s);
		
	}
}
}.start();
new Thread(){
@Override
public void run() {
	while(true){
		try {
			String s = br.readLine();
			System.out.println(new Date(System.currentTimeMillis())+":"+s);
			
		} catch (IOException e) {
				e.printStackTrace();
		}

	}
}
}.start();

    }




Last modification:June 9th, 2019 at 08:14 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment