1. 程式人生 > 實用技巧 >PAT(Advanced Level)A1094. The Largest Generation

PAT(Advanced Level)A1094. The Largest Generation

這些類在java.net包中

package com.bjsxt.net.ip;

import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
/**
 * 沒有封裝埠
 * @author Administrator
 *
 */
public class InetDemo01 {

    /**
     * @param args
     * @throws UnknownHostException 
     * 
@throws MalformedURLException */ public static void main(String[] args) throws UnknownHostException{ //使用getLocalHost方法建立InetAddress物件 InetAddress addr = InetAddress.getLocalHost(); System.out.println(addr.getHostAddress()); //返回:192.168.1.100 System.out.println(addr.getHostName()); //
輸出計算機名 //根據域名得到InetAddress物件 addr = InetAddress.getByName("www.163.com"); System.out.println(addr.getHostAddress()); //返回 163伺服器的ip:61.135.253.15 System.out.println(addr.getHostName()); //輸出:www.163.com //根據ip得到InetAddress物件 addr = InetAddress.getByName("61.135.253.15"); System.out.println(addr.getHostAddress());
//返回 163伺服器的ip:61.135.253.15 System.out.println(addr.getHostName()); //輸出ip而不是域名。如果這個IP地 址不存在或DNS伺服器不允許進行IP地址和域名的對映,getHostName方法就直接返回這個IP地址。 } }
View Code

package com.bjsxt.net.ip;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

/**
 * 封裝埠:在InetAddress基礎上+埠
 * @author Administrator
 *
 */
public class InetSockeDemo01 {

    /**
     * @param args
     * @throws UnknownHostException 
     */
    public static void main(String[] args) throws UnknownHostException {
        InetSocketAddress  address = new InetSocketAddress("127.0.0.1",9999);//一般用這個,下邊那個不常用
        address = new InetSocketAddress(InetAddress.getByName("127.0.0.1"),9999);
        System.out.println(address.getHostName());
        System.out.println(address.getPort());
        InetAddress addr =address.getAddress();
        System.out.println(addr.getHostAddress());  //返回:地址
        System.out.println(addr.getHostName());  //輸出計算機名
        
    }

}
View Code

package feng.li.net;

import java.net.MalformedURLException;
import java.net.URL;

public class URL1 {

    /**
     * @param args
     * @throws MalformedURLException 
     */
    public static void main(String[] args) throws MalformedURLException {
        // TODO Auto-generated method stub
        URL url = new URL("http://www.baidu.com:80/index.html#?uname=bjsxt");
        System.out.println("協議:"+url.getProtocol());
        System.out.println("域名:"+url.getHost());
        System.out.println("埠:"+url.getPort());
        System.out.println("資源:"+url.getFile());
        System.out.println("相對路徑:"+url.getPath());
        System.out.println("錨點:"+url.getRef()); //錨點#後面的內容
        System.out.println("引數:"+url.getQuery());//?引數 :存在錨點  返回null ,不存在,返回正確
        
        
        
        
        
        url = new URL("http://www.baidu.com:80/a/");
        url = new URL(url,"b.txt"); //相對路徑
        System.out.println(url.toString());

    }

}
View Code
package feng.li.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;

public class URL2 {
    public static void main(String[] args) throws UnsupportedEncodingException, IOException{
        URL url = new URL("http://www.baidu.com"); //主頁 預設資源
        
        //獲取資源 網路流
        /*
        InputStream is =url.openStream(); 
        byte[] flush = new byte[1024];
        int len =0;
        while(-1!=(len=is.read(flush))){
            System.out.println(new String(flush,0,len));
        }
        is.close();
        */
        
        //下面程式碼解決亂碼問題,也可以手動改,字符集一致,下面用的是轉換流的方法
        BufferedReader  br = 
                new BufferedReader(new InputStreamReader(url.openStream(),"utf-8"));
        //BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("baidu2.html"),"utf-8"));
        
        String msg =null;
        while((msg=br.readLine())!=null){
            System.out.println(msg);
            //bw.append(msg);
            //bw.newLine();
        }
        //bw.flush();
        
        //bw.close();
        br.close();
        
        
        
    
    }

}
View Code

package feng.li.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class myClient {

/**
 * 客戶端
 * 1、建立客戶端 +埠
 * 2、準備資料
 * 3、打包(傳送的地點 及埠)
 * 4、傳送
 * 5、釋放
 * @author Administrator
 * @throws IOException 
 *
 */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        //1、建立客戶端 +埠
        DatagramSocket client = new DatagramSocket(6666);
        //2、準備資料
        String msg ="udp程式設計";
        byte[] data =msg.getBytes();
        //3、打包(傳送的地點 及埠) DatagramPacket(byte[] buf, int length, InetAddress address, int port)
        DatagramPacket packet = new DatagramPacket(data,data.length,new InetSocketAddress("localhost",8888));
        //4、傳送
        client.send(packet);
        //5、釋放
        client.close();
        
    }

}
View Code
package feng.li.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class myServer {

    /**
     * 服務端
     * 1、建立服務端 +埠
     * 2、準備接受容器
     * 3、封裝成 包
     * 4、接受資料
     * 5、分析資料  
     * 6、釋放
     * @author Administrator
     * @throws IOException 
     *
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        //1、建立服務端 +埠
        DatagramSocket server = new DatagramSocket(8888);
        //2、準備接受容器
        byte[] container = new byte[1024];
        //3、封裝成 包 DatagramPacket(byte[] buf, int length)         
        DatagramPacket packet =new DatagramPacket(container, container.length) ;
        //4、接受資料
        server.receive(packet);
        //5、分析資料
        byte[] data =packet.getData();
        int len =packet.getLength();
        System.out.println(new String(data,0,len));
        //6、釋放
        server.close();
    }

}
View Code

注:瀏覽器也是一個基於TCP的客戶端,我們也可以自己寫一個客戶端

package feng.li.tcp;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class server {

    /**
     必須先啟動伺服器 後連線
    1、建立伺服器  指定埠   ServerSocket(int port) 
    2、接收客戶端連線  
    3、傳送資料+接收資料
     * @throws IOException 
    * 
    */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        //1、建立伺服器  指定埠   ServerSocket(int port) 
        ServerSocket server = new ServerSocket(8888);
        //2、接收客戶端連線   阻塞式
        Socket socket =server.accept();
        System.out.println("一個客戶端建立連線");
        //3、傳送資料
        String msg ="歡迎使用";
        //輸出流
        /*
        BufferedWriter bw = new BufferedWriter(
                new OutputStreamWriter(
                socket.getOutputStream()));
        
        bw.write(msg);
        bw.newLine();
        bw.flush();
        
        
        */
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        dos.writeUTF(msg);
        dos.flush();

    }

}
View Code
package feng.li.tcp;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class client {

    /**
     1、建立客戶端   必須指定伺服器+埠    此時就在連線
         Socket(String host, int port) 
     2、接收資料 +傳送資料    
     * @author Administrator
     * @throws IOException 
     * @throws UnknownHostException 
     *
     */
    public static void main(String[] args) throws UnknownHostException, IOException {
        // TODO Auto-generated method stub
        //1、建立客戶端   必須指定伺服器+埠    此時就在連線
        Socket client = new Socket("localhost",8888);
        //2、接收資料
        /*
         * 使用buffer要注意是行讀取,所讀內容要麼有\r\n,要麼使用newLine()方法
        BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
        String echo =br.readLine(); //阻塞式方法
        System.out.println(echo);
        */
        DataInputStream dis = new DataInputStream(client.getInputStream());
        String echo = dis.readUTF();
        System.out.println(echo);

    }

}
View Code

群聊(多執行緒,伺服器對應多個執行緒即多個客戶端)

Demo1

package Demo1;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class Client {

    /**
     * 建立客戶端: 傳送資料+接收資料
     * 寫出資料:輸出流
     * 讀取資料:輸入流
     * 
        輸入流 與輸出流 在同一個執行緒內 應該 獨立處理,彼此獨立
      
     * @author Administrator
     * @throws IOException 
     *
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        Socket client = new Socket("localhost",9999);
        //控制檯輸入流
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        DataOutputStream dos = new DataOutputStream(client.getOutputStream());
        DataInputStream dis = new DataInputStream(client.getInputStream());
        while(true){
            String info =console.readLine();
            //輸出流
            dos.writeUTF(info);
            dos.flush();
            //輸入流
            String msg =dis.readUTF();
            System.out.println(msg);
        }

    }

}
View Code
package Demo1;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    /**
     * 建立伺服器
     * 寫出資料:輸出流
     * 讀取資料:輸入流
     * @author Administrator
     * @throws IOException 
     *
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        ServerSocket server =new ServerSocket(9999);
        Socket client =server.accept();
        
        //寫出資料
        //輸入流
        DataInputStream dis = new DataInputStream(client.getInputStream());
        String msg =dis.readUTF();
        //輸出流
        DataOutputStream dos = new DataOutputStream(client.getOutputStream());
        dos.writeUTF("伺服器-->"+msg);
        dos.flush();

    }

}
View Code

Demo2

client

package Demo2;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 建立客戶端: 傳送資料+接收資料
 * 寫出資料:輸出流
 * 讀取資料:輸入流
 * 
    輸入流 與輸出流 在同一個執行緒內 應該 獨立處理,彼此獨立
    
    
    
 * 
 * 
 * 
 * @author Administrator
 *
 */
public class Client {

    /**
     * @param args
     * @throws IOException 
     * @throws UnknownHostException 
     */
    public static void main(String[] args) throws UnknownHostException, IOException {
        Socket client = new Socket("localhost",9999);
        new Thread(new Send(client)).start(); //一條路徑
        new Thread(new Receive(client), null).start(); //一條路徑
        
    }

}
View Code

server

package Demo2;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 建立伺服器
 * 寫出資料:輸出流
 * 讀取資料:輸入流
 * @author Administrator
 *
 */
public class Server {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        ServerSocket server =new ServerSocket(9999);
        while(true){
            Socket client =server.accept();        
            //寫出資料
            //輸入流
            DataInputStream dis = new DataInputStream(client.getInputStream());
            DataOutputStream dos = new DataOutputStream(client.getOutputStream());
            
            while(true){
                String msg =dis.readUTF();
                System.out.println(msg);
                //輸出流
                dos.writeUTF("伺服器-->"+msg);
                dos.flush();
            }
        }
        
        
        
        
        
    }

}
View Code

send

package Demo2;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
/**
 * 傳送資料 執行緒
 * @author Administrator
 *
 */
public class Send implements Runnable {
    //控制檯輸入流
    private BufferedReader console;
    //管道輸出流
    private DataOutputStream dos;
    //控制執行緒
    private boolean isRunning =true;
    public Send() {
        console =new BufferedReader(new InputStreamReader(System.in));
    }
    public Send(Socket client){
        this();
        try {
            dos =new DataOutputStream(client.getOutputStream());
        } catch (IOException e) {
            //e.printStackTrace();
            isRunning =false;
            CloseUtil.closeAll(dos,console);
            
        }
    }
    //1、從控制檯接收資料
    private String getMsgFromConsole(){
        try {
            return console.readLine();
        } catch (IOException e) {
            //e.printStackTrace();
        }
        return "";
    }
    /**
     * 1、從控制檯接收資料
     * 2、傳送資料
     */
    public void send(){
        String msg = getMsgFromConsole();
        try {
            if(null!=msg&& !msg.equals("")){
                dos.writeUTF(msg);
                dos.flush(); //強制重新整理
            }
        } catch (IOException e) {
            //e.printStackTrace();
            isRunning =false;
            CloseUtil.closeAll(dos,console);
        }
    }
    
    
    public void run() {
        //執行緒體
        while(isRunning){
            send();
        }
    }
}
View Code

receive

package Demo2;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * 接收執行緒 
 * @author Administrator
 *
 */
public class Receive implements Runnable {
    //輸入流
    private  DataInputStream dis ;
    //執行緒標識
    private boolean isRunning = true;
    public Receive() {
    }
    public Receive(Socket client){
        try {
            dis = new DataInputStream(client.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            isRunning =false;
            CloseUtil.closeAll(dis);
        }
    }
    /**
     * 接收資料
     * @return
     */
    public String  receive(){
        String msg ="";
        try {
            msg=dis.readUTF();
        } catch (IOException e) {
            e.printStackTrace();
            isRunning =false;
            CloseUtil.closeAll(dis);
        }
        return msg;
    }
    public void run() {
        //執行緒體
        while(isRunning){
            System.out.println(receive());
        }
    }
}
View Code

closeUtil

package Demo2;

import java.io.Closeable;

/**
 * 關閉流的方法
 * @author Administrator
 *
 */
public class CloseUtil {
    public static void closeAll(Closeable... io){
        for(Closeable temp:io){
            try {
                if (null != temp) {
                    temp.close();
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }
}
View Code

Demo3

client

package com.bjsxt.net.tcp.chat.demo03;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 建立客戶端: 傳送資料+接收資料
 * 寫出資料:輸出流
 * 讀取資料:輸入流
 * 
    輸入流 與輸出流 在同一個執行緒內 應該 獨立處理,彼此獨立
    
    
    
 * 
 * 
 * 
 * @author Administrator
 *
 */
public class Client {

    /**
     * @param args
     * @throws IOException 
     * @throws UnknownHostException 
     */
    public static void main(String[] args) throws UnknownHostException, IOException {
        Socket client = new Socket("localhost",9999);
        new Thread(new Send(client)).start(); //一條路徑
        new Thread(new Receive(client)).start(); //一條路徑
        
    }

}
View Code

server

package com.bjsxt.net.tcp.chat.demo03;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 建立伺服器
 * 寫出資料:輸出流
 * 讀取資料:輸入流
 * @author Administrator
 *
 */
public class Server {
    private List<MyChannel> all = new ArrayList<MyChannel>();
    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        new Server().start();    
        
    }
    
    public void start() throws IOException{
        ServerSocket server =new ServerSocket(9999);
        while(true){
            Socket client =server.accept();        
            MyChannel channel = new MyChannel(client);
            all.add(channel);//統一管理
            new Thread(channel).start(); //一條道路
        }
    }
    
    
    /**
     * 一個客戶端 一條道路
     * 1、輸入流
     * 2、輸出流
     * 3、接收資料
     * 4、傳送資料
     * @author Administrator
     *
     */
    private class MyChannel implements Runnable{
        private DataInputStream dis ;
        private DataOutputStream dos ;
        private boolean isRunning =true;
        public MyChannel(Socket client ) {
            try {
                dis = new DataInputStream(client.getInputStream());
                dos = new DataOutputStream(client.getOutputStream());
            } catch (IOException e) {
                //e.printStackTrace();
                CloseUtil.closeAll(dis,dos);
                isRunning =false;
            }
        }
        /**
         * 讀取資料
         * @return
         */
        private String receive(){
            String msg ="";
            try {
                msg=dis.readUTF();
            } catch (IOException e) {
                //e.printStackTrace();
                CloseUtil.closeAll(dis);
                isRunning =false;
                all.remove(this); //移除自身
            }
            return msg;
        }
        
        /**
         * 傳送資料
         */
        private void send(String msg){
            if(null==msg ||msg.equals("")){
                return ;
            }
            try {
                dos.writeUTF(msg);
                dos.flush();
            } catch (IOException e) {
                //e.printStackTrace();
                CloseUtil.closeAll(dos);
                isRunning =false;
                all.remove(this); //移除自身
            }
        }
        
        /**
         * 傳送給其他客戶端
         */
        private void sendOthers(){
            String msg = this.receive();
            //遍歷容器
            for(MyChannel other:all){
                if(other ==this){
                    continue;
                }
                //傳送其他客戶端
                other.send(msg);
            }
        }
        
        
        @Override
        public void run() {
            while(isRunning){
                sendOthers();
            }
        }
    }
    

}
View Code

send

package com.bjsxt.net.tcp.chat.demo03;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * 傳送資料 執行緒
 * @author Administrator
 *
 */
public class Send implements Runnable{
    //控制檯輸入流
    private BufferedReader console;
    //管道輸出流
    private DataOutputStream dos;
    //控制執行緒
    private boolean isRunning =true;
    public Send() {
        console =new BufferedReader(new InputStreamReader(System.in));
    }
    public Send(Socket client){
        this();
        try {
            dos =new DataOutputStream(client.getOutputStream());
        } catch (IOException e) {
            //e.printStackTrace();
            isRunning =false;
            CloseUtil.closeAll(dos,console);
            
        }
    }
    //1、從控制檯接收資料
    private String getMsgFromConsole(){
        try {
            return console.readLine();
        } catch (IOException e) {
            //e.printStackTrace();
        }
        return "";
    }
    /**
     * 1、從控制檯接收資料
     * 2、傳送資料
     */
    public void send(){
        String msg = getMsgFromConsole();
        try {
            if(null!=msg&& !msg.equals("")){
                dos.writeUTF(msg);
                dos.flush(); //強制重新整理
            }
        } catch (IOException e) {
            //e.printStackTrace();
            isRunning =false;
            CloseUtil.closeAll(dos,console);
        }
    }
    
    
    @Override
    public void run() {
        //執行緒體
        while(isRunning){
            send();
        }
    }

}
View Code

receive

package com.bjsxt.net.tcp.chat.demo03;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * 接收執行緒 
 * @author Administrator
 *
 */
public class Receive implements Runnable {
    //輸入流
    private  DataInputStream dis ;
    //執行緒標識
    private boolean isRunning = true;
    public Receive() {
    }
    public Receive(Socket client){
        try {
            dis = new DataInputStream(client.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            isRunning =false;
            CloseUtil.closeAll(dis);
        }
    }
    /**
     * 接收資料
     * @return
     */
    public String  receive(){
        String msg ="";
        try {
            msg=dis.readUTF();
        } catch (IOException e) {
            e.printStackTrace();
            isRunning =false;
            CloseUtil.closeAll(dis);
        }
        return msg;
    }
    @Override
    public void run() {
        //執行緒體
        while(isRunning){
            System.out.println(receive());
        }
    }
}
View Code

closeUtil

package com.bjsxt.net.tcp.chat.demo03;

import java.io.Closeable;

/**
 * 關閉流的方法
 * @author Administrator
 *
 */
public class CloseUtil {
    public static void closeAll(Closeable... io){
        for(Closeable temp:io){
            try {
                if (null != temp) {
                    temp.close();
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }
}
View Code

Demo4

client

package com.bjsxt.net.tcp.chat.demo04;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 建立客戶端: 傳送資料+接收資料
 * 寫出資料:輸出流
 * 讀取資料:輸入流
 * 
    輸入流 與輸出流 在同一個執行緒內 應該 獨立處理,彼此獨立
    
    加入名稱
    
    
 * 
 * 
 * 
 * @author Administrator
 *
 */
public class Client {

    /**
     * @param args
     * @throws IOException 
     * @throws UnknownHostException 
     */
    public static void main(String[] args) throws UnknownHostException, IOException {
        System.out.println("請輸入名稱:");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String name = br.readLine();
        if(name.equals("")){
            return;
        }
        
        Socket client = new Socket("localhost",9999);
        new Thread(new Send(client,name)).start(); //一條路徑
        new Thread(new Receive(client)).start(); //一條路徑
        
    }

}
View Code

server

package com.bjsxt.net.tcp.chat.demo04;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 建立伺服器
 * 寫出資料:輸出流
 * 讀取資料:輸入流
 * @author Administrator
 *
 */
public class Server {
    private List<MyChannel> all = new ArrayList<MyChannel>();
    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        new Server().start();    
        
    }
    
    public void start() throws IOException{
        ServerSocket server =new ServerSocket(9999);
        while(true){
            Socket client =server.accept();        
            MyChannel channel = new MyChannel(client);
            all.add(channel);//統一管理
            new Thread(channel).start(); //一條道路
        }
    }
    
    
    /**
     * 一個客戶端 一條道路
     * 1、輸入流
     * 2、輸出流
     * 3、接收資料
     * 4、傳送資料
     * @author Administrator
     *
     */
    private class MyChannel implements Runnable{
        private DataInputStream dis ;
        private DataOutputStream dos ;
        private boolean isRunning =true;
        private String name; 
        public MyChannel(Socket client ) {
            try {
                dis = new DataInputStream(client.getInputStream());
                dos = new DataOutputStream(client.getOutputStream());                
                this.name =dis.readUTF();                
                this.send("歡迎您進入聊天室");
                sendOthers(this.name+"進入了聊天室",true);
            } catch (IOException e) {
                //e.printStackTrace();
                CloseUtil.closeAll(dis,dos);
                isRunning =false;
            }
        }
        /**
         * 讀取資料
         * @return
         */
        private String receive(){
            String msg ="";
            try {
                msg=dis.readUTF();
            } catch (IOException e) {
                //e.printStackTrace();
                CloseUtil.closeAll(dis);
                isRunning =false;
                all.remove(this); //移除自身
            }
            return msg;
        }
        
        /**
         * 傳送資料
         */
        private void send(String msg){
            if(null==msg ||msg.equals("")){
                return ;
            }
            try {
                dos.writeUTF(msg);
                dos.flush();
            } catch (IOException e) {
                //e.printStackTrace();
                CloseUtil.closeAll(dos);
                isRunning =false;
                all.remove(this); //移除自身
            }
        }
        
        /**
         * 傳送給其他客戶端
         */
        private void sendOthers(String msg,boolean sys){
            //是否為私聊 約定
            if(msg.startsWith("@")&& msg.indexOf(":")>-1 ){ //私聊
                //獲取name
                String name =msg.substring(1,msg.indexOf(":"));
                String content = msg.substring(msg.indexOf(":")+1);
                for(MyChannel other:all){
                    if(other.name.equals(name)){
                        other.send(this.name+"對您悄悄地說:"+content);
                    }
                }
            }else{        
                //遍歷容器
                for(MyChannel other:all){
                    if(other ==this){
                        continue;
                    }
                    if(sys){ //系統資訊
                        other.send("系統資訊:"+msg);
                    }else{
                        //傳送其他客戶端
                        other.send(this.name+"對所有人說:"+msg);
                    }
                }
            }
        }
        
        
        @Override
        public void run() {
            while(isRunning){
                sendOthers(receive(),false);
            }
        }
    }
    

}
View Code

send

package com.bjsxt.net.tcp.chat.demo04;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * 傳送資料 執行緒
 * @author Administrator
 *
 */
public class Send implements Runnable{
    //控制檯輸入流
    private BufferedReader console;
    //管道輸出流
    private DataOutputStream dos;
    //控制執行緒
    private boolean isRunning =true;
    //名稱
    private String name;
    public Send() {
        console =new BufferedReader(new InputStreamReader(System.in));
    }
    public Send(Socket client,String name){
        this();
        try {
            dos =new DataOutputStream(client.getOutputStream());
            this.name =name;
            send(this.name);
        } catch (IOException e) {
            //e.printStackTrace();
            isRunning =false;
            CloseUtil.closeAll(dos,console);
            
        }
    }
    //1、從控制檯接收資料
    private String getMsgFromConsole(){
        try {
            return console.readLine();
        } catch (IOException e) {
            //e.printStackTrace();
        }
        return "";
    }
    /**
     * 1、從控制檯接收資料
     * 2、傳送資料
     */
    public void send(String msg){
        try {
            if(null!=msg&& !msg.equals("")){
                dos.writeUTF(msg);
                dos.flush(); //強制重新整理
            }
        } catch (IOException e) {
            //e.printStackTrace();
            isRunning =false;
            CloseUtil.closeAll(dos,console);
        }
    }
    
    
    @Override
    public void run() {
        //執行緒體
        while(isRunning){
            send(getMsgFromConsole());
        }
    }

}
View Code

receive

package com.bjsxt.net.tcp.chat.demo04;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * 接收執行緒 
 * @author Administrator
 *
 */
public class Receive implements Runnable {
    //輸入流
    private  DataInputStream dis ;
    //執行緒標識
    private boolean isRunning = true;
    public Receive() {
    }
    public Receive(Socket client){
        try {
            dis = new DataInputStream(client.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            isRunning =false;
            CloseUtil.closeAll(dis);
        }
    }
    /**
     * 接收資料
     * @return
     */
    public String  receive(){
        String msg ="";
        try {
            msg=dis.readUTF();
        } catch (IOException e) {
            e.printStackTrace();
            isRunning =false;
            CloseUtil.closeAll(dis);
        }
        return msg;
    }
    @Override
    public void run() {
        //執行緒體
        while(isRunning){
            System.out.println(receive());
        }
    }
}
View Code

closeUtil

package com.bjsxt.net.tcp.chat.demo04;

import java.io.Closeable;

/**
 * 關閉流的方法
 * @author Administrator
 *
 */
public class CloseUtil {
    public static void closeAll(Closeable... io){
        for(Closeable temp:io){
            try {
                if (null != temp) {
                    temp.close();
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }
}
View Code