Socket+다 중 스 레 드 구현 콘 솔 채 팅 방

2984 단어 Web자바
링크
client.java:
//  github:https://github.com/ygj0930
//    :http://www.cnblogs.com/ygj0930/
import java.io.*;
import java.net.*;
import java.util.*;

public class Client{
	public int port=8080;
	Socket socket=null;
	
	public static void main(String[] args)
	{
		new Client();
	}
	
	public Client()
	{
		 
		try {  
		    socket=new Socket("127.0.0.1",port);
			
			new Cthread().start();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(socket  
                  .getInputStream()));  
            String msg1;  
            while ((msg1 = br.readLine()) != null) { 
							
                System.out.println(msg1);  
			}
		}catch (Exception e) {  
  
			} 
			
		
	}
	
	class Cthread extends Thread
	{
		 
			public void run() {  
            try {  
			
				BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
                PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);  
                String msg2;  
  
                while (true) {  
				
                    msg2 = re.readLine();  
                    pw.println(msg2);  
                }  
            }catch (Exception e) {  
                e.printStackTrace();  
            }  
		
	
		}
	}

}

Server.java:
//  github:https://github.com/ygj0930
//    :http://www.cnblogs.com/ygj0930/
import java.net.*;
import java.io.*;
import java.util.*;

public class Server
{      int port;
	   List clients;
	   ServerSocket server;
	public static void main(String[] args)
	{
		new Server();
	}
	public Server()
	{   
	try{
	   
	   port=8080;
	   clients=new ArrayList();
	   server=new ServerSocket(port);
		
		while(true)
	    {
		
		Socket socket=server.accept();
		clients.add(socket);
		Mythread mythread=new Mythread(socket);
		mythread.start();
		}
		
		
		
	}catch(Exception ex)
	{ 
	}
   }
 class Mythread extends Thread
 {
	 Socket ssocket;
	 private BufferedReader br;  
	 private PrintWriter pw;  
	 public  String msg; 
	 public Mythread(Socket s)
	 {
		 ssocket=s;
	 }
	public void run()
	{
				
				try{
		 br = new BufferedReader(new InputStreamReader(ssocket.getInputStream()));  
		 msg = "  【" + ssocket.getInetAddress() + "】     !      【"  
                    + clients.size() + "】 "; 
				
		sendMsg();
				
                while ((msg = br.readLine()) != null) {  
                    
                        msg = "【" + ssocket.getInetAddress() + "】 :" + msg;  
                        sendMsg();  
                    
                } 
				}catch(Exception ex)
				{
					
				}				
     }
	public void sendMsg()
	{
			try{
			System.out.println(msg);
			
			for(int i = clients.size() - 1; i >= 0; i--)
			{
				pw=new PrintWriter(clients.get(i).getOutputStream(),true);
				pw.println(msg);
				
				pw.flush();
			}
			
			}catch(Exception ex)
			{
				
			}
	}	
        

 } 
   
   
   
}

좋은 웹페이지 즐겨찾기