JAVA实现C/S通讯

来源:互联网 发布:淘宝宝贝主图怎么修改 编辑:程序博客网 时间:2024/06/05 06:44

客户端。
1,服务端点。
2,读取客户端输入的数据。
3,通过socket 输出流将数据发给服务端。
4,读取服务端反馈信息。
5,关闭。

服务端
1,创建绑定到特定端口的服务器

为了可以让多个客户端同时并发访问服务端。
服务端最好就是将每个客户端封装到一个单独的线程中,这样,就可以同时处理多个客户端请求。

如何定义多线程呢?
只要明确了每一个客户端要在服务端执行的代码即可。将该代码存入run方法中。
2,读取客户端数据。
3,通过socket 输出流将数据发给其他客户端。

源码

import java.awt.*;import java.awt.event.*;import java.net.*;import java.io.*;public class  ChatClient extends Frame{           Socket s = null;    DataOutputStream dos = null;    DataInputStream dis = null;    private boolean bConnected = false;        TextField tf = new TextField();         TextArea  ta = new TextArea();        //创建一个线程对象        Thread tRecv = new Thread(new RecvThread());     public static void main(String[] args)     {        new ChatClient().launchFrame();    }//创建窗体    public void  launchFrame()    {           setLocation(500,500);        this.setSize(200,200);        add(tf,BorderLayout.SOUTH);        add(ta,BorderLayout.NORTH);        pack();        //设置关闭窗口        this.addWindowListener(new WindowAdapter()        {            public void windowClosing(WindowEvent e)            {   if(s==null)                System.exit(0);                else                 //调用全部关闭资源方法                disconnect();                System.exit(0);            }        });        tf.addActionListener(new TFListener());        setVisible(true);        connect();        tRecv.start();    }    //创建客户端    public void connect()    {        try        {            s = new Socket("127.0.0.1",8888);            //            dos = new DataOutputStream(s.getOutputStream());            dis = new DataInputStream(s.getInputStream());            System.out.println("我连上了");            bConnected = true;        }        catch (ConnectException e)        {            System.out.println("服务端未建立");        }        catch (UnknownHostException e)        {            e.printStackTrace();        }        catch (IOException e)        {               e.printStackTrace();        }    }    //关闭全部资源方法    public void disconnect()    {        try        {   s.close();            dos.close();            dis.close();        }        catch (IOException e)        {            e.printStackTrace();        }        /*        try {            bConnected = false;            tRecv.join();        } catch(InterruptedException e) {            e.printStackTrace();        } finally {            try {                dos.close();                dis.close();                s.close();            } catch (IOException e) {                e.printStackTrace();            }        }        */    }    //创建一个监听窗体的动作的对象    private class TFListener implements  ActionListener    {        public void actionPerformed(ActionEvent e)        {               String str =tf.getText().trim();            tf.setText("");            try            {                dos.writeUTF(str);                dos.flush();            }            catch(IOException e1)            {                e1.printStackTrace();            }        }    }        //创建一个线程来读取服务器反馈的信息    private class RecvThread implements Runnable    {        public void run()        {            try            {                while(bConnected){                    String str = dis.readUTF();                    ta.setText(ta.getText() + str + '\n');                }            }            catch (SocketException e) {                System.out.println("退出了,bye!");            } catch (EOFException e) {                System.out.println("推出了,bye - bye!");            }            catch(IOException e) {                e.printStackTrace();            }         }    }}
import java.net.*;import java.io.*;import java.util.*;public class ChatServer{       boolean started = false;        ServerSocket ss = null;    //用一个集合记录线程的信息    List<Client> clients = new ArrayList<Client>();    public static void main( String[] args)    {        new ChatServer().start();    }            //创建服务端    public void start()    {        try        {   //创建绑定到特定端口的服务器套接字。            ss = new ServerSocket(8888);            started = true;        }        catch(BindException e)        {            System.out.println("端口使用中.请关闭程序 并重新启动");            System.exit(0);        }        catch(IOException e)        {            e.printStackTrace();        }        try        {            while (started)            {                   //侦听并接受到此套接字的连接。此方法在连接传入之前一直阻塞。                Socket s = ss.accept();                 Client c = new Client(s);                //String ip = s.getInetAddress().getHostAddress();                System.out.println("客户端来了");                new Thread(c).start();//开启线程                clients.add(c);            }        }        catch (IOException e) {            e.printStackTrace();        } finally {            try {                ss.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }        //创建线程    class Client implements Runnable    {           private Socket s;        private DataInputStream dis = null;        private DataOutputStream dos = null;        private boolean bConnected = false;    public Client(Socket s)        {            this.s = s;            try            {                dis = new DataInputStream(s.getInputStream());                dos = new DataOutputStream(s.getOutputStream());                bConnected = true;            }            catch(IOException e)            {                   e.printStackTrace();            }        }        public void send(String str)        {               try {                dos.writeUTF(str);            }             catch (SocketException e) {                //clients.remove(this);                System.out.println("对方退出了");                }            catch (IOException e) {                e.printStackTrace();            }        }    //线程运行方法    public void run()    {        try        {            while (bConnected)            {                String ip = s.getInetAddress().getHostAddress();                String str = ip+"说:"+dis.readUTF();System.out.println(str);                for(int i=0; i<clients.size(); i++)                     {                        Client c = clients.get(i);                        c.send(str);                    }                    /*                    for(Iterator<Client> it = clients.iterator(); it.hasNext(); ) {                        Client c = it.next();                        c.send(str);                    }                    */                    /*                    Iterator<Client> it = clients.iterator();                    while(it.hasNext()) {                        Client c = it.next();                        c.send(str);                    }*/            }               }        catch (EOFException e) {            System.out.println("客户端关闭了");        }        catch (IOException e)        {            e.printStackTrace();        }//最终关闭所有资源        finally        {            try            {                if(dis != null)                     dis.close();                if(dos != null)                     dos.close();                if(s != null)                     s.close();                    clients.remove(this);            }            catch (IOException e1)            {                   e1.printStackTrace();            }        }    }}}
0 0
原创粉丝点击