利用Socket类,自学相关内容,实现一命令行环境下简易网络聊天室,要求包括:1. 独立运行的服务器端和客户端 2. 自学多线程内容,实现多人同时在线聊天

//服务器端:
import java.io.*;
import java.util.Scanner;
import java.net.ServerSocket;
import java.net.Socket;
class EchoThread implements Runnable{
  private Socket client; 
  public EchoThread(Socket client){
    this.client=client;
  }
  public void run(){
    try{
    Scanner in=new Scanner(client.getInputStream());
    PrintStream out=new PrintStream(client.getOutputStream());
    boolean flag=true; 
    String str;
    while(flag){
      if(in.hasNext()){
        str=in.next().trim();
        if(str.equalsIgnoreCase("byebye")){
          flag=false;
        }
        else 
          out.println("Echo"+str);
      }
    }
    client.close();
    out.close();
    in.close();
    }catch(IOException e){
      e.printStackTrace();
    }
  }
}
public class lab01{
  public static void main(String args[]) throws Exception{
    ServerSocket ser=new ServerSocket(9999);
    boolean flag=true;
    while(flag){
      Socket client=ser.accept();
      new Thread(new EchoThread(client)).start();
    }
  }
}

 
 
//客户端
import java.io.*; import java.util.Scanner; import java.net.Socket; public class lab2{ public static void main(String args[]) throws Exception{ Socket client=new Socket("localhost",9999); Scanner scan=new Scanner(System.in); Scanner in=new Scanner(client.getInputStream()); PrintStream out=new PrintStream(client.getOutputStream()); boolean flag=true; String str; while(flag){ str=scan.nextLine(); if(str.equalsIgnoreCase("byebye")){ flag=false; } else out.println(str); if(in.hasNext()){ System.out.println(in.next()); } } scan.close(); in.close(); out.close(); client.close(); } }

猜你喜欢

转载自blog.csdn.net/qq_38448815/article/details/80245232