1. 程式人生 > >Java簡易多人聊天室(cmd下執行)

Java簡易多人聊天室(cmd下執行)

思路:

1.首先建立伺服器監聽
ServerSocket server = new ServerSocket(5000);
監聽某個指定埠號是否有連線請求

2.客戶端發起請求,也就是new了一個Socket socket = new Socket(host,port);
想某個指定埠號發起請求

3.連線確認
當伺服器通過accept()方法接受來自客戶端的請求
Socket socket = server.accpet();//返回一個Socket物件來處理與客戶端的通訊
然後建立一個執行緒來處理
new Thread(new SeverStream(socekt,number)).start();
每收到一個客戶端請求,伺服器建立一個執行緒來處理客戶端的請求

package exercise01;
import java.net.*;
import java.io.*;

public class ChatServer {

	public static void main(String[] args) throws IOException{
		ServerSocket serverSocket = new ServerSocket(5000);//監聽某個特定埠號
		int number = 1;
		while(true)
		{
			Socket socket = serverSocket.accept();//客戶端傳送請求
			System.out.println("客戶端"+number+"連結成功");
                        //開啟一個新執行緒來處理客戶端的請求
			new Thread(new ServerStream(socket,number)).start();
			number++;
		}
		
	}
}
package exercise01;
import java.net.*;
import java.io.*;

public class ChatClient {

	public static void main(String[] args) throws IOException{
                //向伺服器傳送請求
		Socket socket = new Socket(InetAddress.getLocalHost(),5000);
                //獲取鍵盤輸入流
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                //用來向伺服器傳送訊息
 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
       // BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        while(true)
        {
        	String line = br.readLine();
        	bw.write(line);
        	bw.newLine();//這裡是表示一條訊息的完成以回車為結束符
        	bw.flush();//把緩衝流重新整理
        	if(line.equals("over"))
        		break;
        }
        bw.close();
        br.close();
        socket.close();
	}

}

package exercise01;
import java.net.*;
import java.io.*;

public class ServerStream implements Runnable {
    private Socket socket = null;
    private int number;
    
    public ServerStream(Socket socket,int number)
    {
    	this.socket = socket;
    	this.number = number;
    }
    
	public void run() 
	{
		try 
		{
                        //接受客戶端傳送的訊息
			BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter pw = new PrintWriter(socket.getOutputStream());
			while(true)
            {
            	String line = br.readLine();//讀取字串
            	if(line.equals("over"))
            		break;
            	System.out.println("客戶端"+number+"說:"+line);
            }
		}
		catch(IOException e)
		{
			
		}
		
		finally {
			
			try {
				socket.close();
			}
			catch(IOException e)
			{
				
			}
		}
		
	}	
}