다 중 스 레 드 를 이용 하여 채 팅 방 의 기능 을 실현 하 다.

서버 가 클 라 이언 트 로부터 메 시 지 를 받 으 면 모든 클 라 이언 트 에 게 보 냅 니 다!서버 가 주동 적 으로 밀 었 습 니 다!1 서버 는 클 라 이언 트 목록 을 가지 고 있 습 니 다. clientPoolr 2 클 라 이언 트 는 하위 스 레 드 를 만 들 고 서버 에서 보 낸 메 시 지 를 계속 받 아야 합 니 다.
//          
class ClientChatThread extends Thread{
	private Socket client;

	public ClientChatThread(Socket client) {
		super();
		this.client = client;
	}
	//         
	private void sendAll(String str){
		for(ClientChatThread ct:CustomThreadPoolAutoReplyTcpServer.pool){
			try {
				DataOutputStream dos = new DataOutputStream(ct.client.getOutputStream());
				dos.writeUTF(str);
			} catch (Exception e) {
				System.out.println("      ["+ct.client.getPort()+"]  ,      ");
			}
		}
	}
	//           
	@Override
	public void run() {
		try {
			DataOutputStream dos = new DataOutputStream(client.getOutputStream());
			DataInputStream dis = new DataInputStream(client.getInputStream());
			while (true) {
				// try     ,           
				try {
					//           
					String str = dis.readUTF();//        
					System.out.println(str);
					//                
					//        
					sendAll(str);
				} catch (Exception e) {
					System.out.println("    [" + client.getPort() + "]    ");
					//         
					CustomThreadPoolAutoReplyTcpServer.pool.remove(this);
					System.out.println("      :"+CustomThreadPoolAutoReplyTcpServer.pool.size());
					break;
				}
			} 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
//                  
public class CustomThreadPoolAutoReplyTcpServer {
	public static 	Vector<ClientChatThread> pool=new Vector<>();//   ,    
	public static void main(String[] args) throws IOException {
		ServerSocket ss = new ServerSocket(6667);
		System.out.println("     6666      ,       ...");	
		while (true) {
			//     
			Socket client = ss.accept();
			System.out.println("   [" + client.getPort() + "]    ");
			ClientChatThread ct=new ClientChatThread(client);
			pool.add(ct);//      
			System.out.println("      :"+pool.size());
			ct.start();//    
		}
	}
}
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

class ReceiverServerThread extends Thread{
	private Socket client;
	
	public ReceiverServerThread(Socket client) {
		super();
		this.client = client;
	}
	@Override
	public void run() {
		DataInputStream dis =null;
		try {
			dis = new DataInputStream(client.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
		while(true){
			
			String response;
			try {
				response = dis.readUTF();
				System.out.println(response);//       
			} catch (IOException e) {
				System.out.println("         !");
				return;
			}
			
		}
	}
}
public class MultiplyPeopleTcpClient {
	public static void main(String[] args) throws UnknownHostException, IOException {
		System.out.println("      :");
		Scanner sc=new Scanner(System.in);
		String name=sc.nextLine();
		Socket client=new Socket("127.0.0.1",6667);
		System.out.println("     127.0.0.1  ");
		//             
		new ReceiverServerThread(client).start();
		DataOutputStream dos = new DataOutputStream(client.getOutputStream());
		String str="";
		while(!"quit".equals(str=sc.nextLine())){
			dos.writeUTF(name+":"+str);//            
		}
		client.close();//        
	}
}

좋은 웹페이지 즐겨찾기