TCP聊天(实现群聊与私聊的功能)

server端


/**
 * 私聊
 */
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.jar.Attributes.Name;

public class server {

    private ArrayList all  = new ArrayList();  //建立管道容器,以统一管理
    public static void main(String[] args) throws IOException { 
        new server().start();
    }
    /**
     * 启动服务器函数
     * @throws IOException
     */
    private void start() throws IOException
    {
        ServerSocket server = new ServerSocket(9999);
        while (true)
        {
            Socket client = server.accept();
            Mychannel mychannel = new Mychannel(client);  
            all.add(mychannel); //to manage together
            new Thread(mychannel).start(); //one channel
        }
    }

    /**
     * 建立内部类—消息管道类,为实现每个客户端建立独立的一个线程
     * @author lzd
     *
     */

    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());
                name = dis.readUTF();
            } catch (IOException e) {
                isRunning = false;
                CloseUtil.closeAll(dis,dos);
                //e.printStackTrace();      
            }
            send("System News: welcome to "+name);
            sentothers("System News: "+name+" online now",true);
        }

        /**
         * 实现消息获取
         * @return
         */

        private String receipt()
        {
            String mString ="";
            try {
                mString  = dis.readUTF();
            } catch (IOException e) {
                CloseUtil.closeAll(dis);
                isRunning = false;
                all.remove(this);
            }
            return mString;
        }
        /**
         * 实现发送消息
         * @param mString
         */
        private void send(String mString) {
            try {
                dos.writeUTF(mString );
                dos.flush();
            } catch (IOException e) {
                CloseUtil.closeAll(dos);
                isRunning = false;
                all.remove(this);
            }   
        }

        /**
         * 实现分发功能
         */
        private void sentothers(String mString,boolean b)  
        {
            if(mString.startsWith("@")&&mString.indexOf(':')>-1) //判断是否为私聊信息
            {
                String string = mString.substring(1, mString.indexOf(':')); //提取消息中的对象名即@string:

                String content  = mString.substring(mString.indexOf(':')+1); //提取消息中的内容
                for(Mychannel others :all)
                {
                    if(string.equals(others.name))
                        others.send(this.name+" (private):  "+content);
                }               
            }
            else
            {
                for(Mychannel others :all)
                {
                    if(others == this)
                        continue;
                    /**
                     * 此处判断是否为系统消息,以区别话主
                     */
                    if(b)
                        others.send(mString);
                    else
                        others.send(this.name+" (public) :  "+mString);         
                }
            }
        }
        @Override
        public void run() {
            while(isRunning)
            {
                sentothers(this.receipt(),false); // send to others 
            }   
        }
    }

}

client端


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.jar.Attributes.Name;

public class client {


    public static void main(String[] args) throws IOException {
        System.out.println("please input you name: ");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String name = bufferedReader.readLine();
        if(name.equals(""))
            return;

        Socket client  = new Socket("localhost",9999); //建立客户端(指明server的地址,及端口)
        new Thread(new send(client,name)).start();  //建立发送端线程
        new Thread(new receipt(client)).start();  //建立接收端线程
    }

}

接收包装类,为线程


/**
 * 接收类,为接收线程服务
 */
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

public class receipt implements Runnable{
    private DataInputStream dis;
    private boolean isRunning = true;
    public receipt() {
        // TODO Auto-generated constructor stub
    }
     public receipt(Socket client)
     {  
         try {
            dis = new DataInputStream(client.getInputStream());
        } catch (IOException e) {
            CloseUtil.closeAll(dis);
            isRunning = false;
            //e.printStackTrace();
        }
     }
    public String receipt() {
        String mString ="";
            try {
                mString =   dis.readUTF();
            } catch (IOException e) {
                //e.printStackTrace();
                CloseUtil.closeAll(dis);
                isRunning = false;
            }
            return mString;
    }
    @Override
    public void run()  {
        while(isRunning)
        {
            System.out.println(receipt());
        }

    }
}

发送包装类,为线程服务


/**
 * 发送类,为线程启动服务
 */

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

public class send implements Runnable {
    private DataOutputStream dos ;
    private BufferedReader bufferedReader;
    //private String ms =null;
    private boolean isRunning = true;
    private String name;

    public  send() {
        bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    }
    public send (Socket client,String name)  {
        this();
        this.name = name;

        try {
            dos = new DataOutputStream(client.getOutputStream());
        } catch (IOException e) {
            //e.printStackTrace();
            CloseUtil.closeAll(dos,bufferedReader);
            isRunning = false;
        }   
        send(this.name);
    }
    private String getMsFromconsole(BufferedReader bufferedReader)  {
        try {
            return bufferedReader.readLine();
        } catch (IOException e) {
            //e.printStackTrace();
        }
        return"";   
    }

    private  void  send(String ms)   {


        if(ms!=null&&!ms.equals(""))
        {
            try {
                dos.writeUTF(ms);
                dos.flush();
            } catch (IOException e) {
                CloseUtil.closeAll(dos);
                isRunning = false;
                //e.printStackTrace();
            }
        }

    }
    @Override
    public void run() {
        while(isRunning)
        {
            send(getMsFromconsole(bufferedReader));
        }
    }
}

工具类,写了关闭所有异常的数据传输流


/**
 * 异常关闭数据流通道类
 */
import java.io.Closeable;
import java.io.IOException;

public class CloseUtil {

    public static void closeAll(Closeable... io)
    {
        for(Closeable temp : io)
        {
            if(temp != null)
            {
                try {
                    temp.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

你可能感兴趣的:(java程序)