zoukankan      html  css  js  c++  java
  • Socket编程之旅(服务器与客户端沟通)

    我自己也写了一个这样的程序,不过我参考了这一个代码,而且给了我启发,而且比我的要简洁,就直接上吧。程序中最大的变化就是在服务器端,我已经在关键的地方潜入了解释。好吧,直接上代码。

    服务器端: 

    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class ChatServer {
        public static void main(String args[]) {
            Hashtable<String,DataOutputStream> userList = new Hashtable<String,DataOutputStream>(); 
            String name;
            DataInputStream dis;
            DataOutputStream dos;
            try{
                //监听9999端口
                ServerSocket ss = new ServerSocket(9999);
                //始终是循环接收客户端的请求
                while(true){
                    Socket s = ss.accept();    
                    //获得输入流
                    dis = new DataInputStream(s.getInputStream());
                    //获得输出流
                    dos = new DataOutputStream(s.getOutputStream());
                    //读取客户端传送过来的名字信息
                    name = dis.readUTF();
    //                name = s.getPort()+"";
                    
    //System.out.println("abc"+name);
                    
    //把客户端传送过来的名字信息以及是输出流以键值对的形式保存在Hashtable当中
                    userList.put(name,dos);
                    //把1.客户端传送过来的参数
                    
    //2.输入流对象
                    
    //3. 把(1)和输出流的HashTable
                    
    //作为参数去启动一个线程
                    new MyServerReader(name,dis,userList).start();
                }
            }catch(Exception e){
                e.printStackTrace();    
            }
        }
    }

    class MyServerReader extends Thread{
        private String name;
        private DataInputStream dis;
        private Hashtable<String,DataOutputStream> userList;
        public MyServerReader(String name,DataInputStream dis,Hashtable<String,DataOutputStream> userList ){
            this.name = name;
            this.dis = dis;    
            this.userList = userList;
        }
        public void run(){
            String info;
            try{
                transmitMessage(name + " in!","--Server Info--");    
                //时刻判断输入的字符当中是否包含有bye
                while(true){
                    //时刻读取字符
                    info = dis.readUTF();
                    System.out.println("Server========>"+info);
                    if(info.equals("bye")){
                        DataOutputStream dos = (DataOutputStream)(userList.get(name));
                        Thread.sleep(1000);
                        dos.close();
                        dis.close();
                        userList.remove(name);
                        transmitMessage(name + " out!","--Server Info--");    
                        break;
                    }else if(info.length()>0){
                        //如果输入的字符不是bye,并且是有内容的就把数据发送出去
                        transmitMessage(info,name);    
                    }
                }        
            }catch (Exception e) {
            }
        } 
        public void transmitMessage(String msg,String name){
            Collection doses = userList.values();
            DataOutputStream dos;
            for(Object o: doses){
                dos = (DataOutputStream)o;
                try{
                    //向所有的连接客户端发送信息,这里可以通过扩展发送给指定人
                    dos.writeUTF(name + ":" + msg);
                }catch(Exception e){
                }
            }            
        }  

    客户端:

    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ChatClient {
        private String name;
        private Socket s;
        private DataInputStream dis;
        private DataOutputStream dos;
        private Frame f;
        private TextArea ta;
        private TextField tf;
        private boolean runnable = true;    
            
        public static void main(String args[]) {
            ChatClient cc = new ChatClient();
            cc.createUI();
            cc.inputName();        
            cc.connect();    
            cc.createThread();
        }
        public void createUI(){
            f = new Frame("Client");
            ta = new TextArea();
            ta.setEditable(false);
            tf = new TextField();
            Button send = new Button("Send");
            Panel p = new Panel();
            p.setLayout(new BorderLayout());
            p.add(tf,"Center");
            p.add(send,"East");
            f.add(ta,"Center");
            f.add(p,"South");
            MyClientListener listener = new MyClientListener(this);
            send.addActionListener(listener);
            tf.addActionListener(listener);
            f.addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent e){
                    ChatClient.this.shutDown();    
                }    
            });
            f.setSize(400,400);
            f.setLocation(600,0);
            f.setVisible(true);    
            tf.requestFocus();
        }
        public void inputName(){
            String name = javax.swing.JOptionPane.showInputDialog("Input Your Name:");
            this.setName(name);    
            f.setTitle(name);
        }
        public void connect(){
            try {        
                s = new Socket("127.0.0.1",9999);
                dos = new DataOutputStream(s.getOutputStream());
                dis = new DataInputStream(s.getInputStream());
                dos.writeUTF(name);
            }catch (IOException e) {
                e.printStackTrace();        
            }
        }    
        public void createThread(){
            MyClientReader reader = new MyClientReader(this);
            reader.start(); 
        }
        public void stop(){
            runnable = false;    
        }
        public void shutDown(){
            try{
                dos.writeUTF("bye");
                ta.append("Exit in 5 seconds!");
                this.stop();            
                Thread.sleep(5000);
                dis.close();
                dos.close();
                s.close();
            }catch(Exception e){
            }
            System.exit(0);                        
        }
        public boolean getRunnable(){
            return runnable;
        }            
        public void setName(String name){
            this.name = name;
        }
        public DataInputStream getDataInputStream(){
            return dis;    
        }
        public DataOutputStream getDataOutputStream(){
            return dos;    
        }
        public TextArea getTextArea(){
            return ta;    
        }
        public TextField getTextField(){
            return tf;    
        }
    }

    class MyClientListener implements ActionListener{
        
        private ChatClient client;    
        public MyClientListener(ChatClient client){
            this.client = client;
        }
        public void actionPerformed(ActionEvent e){
            TextField tf = client.getTextField();
            String info = tf.getText();
            try{
                client.getDataOutputStream().writeUTF(info);    
            }catch (IOException e1) {
                e1.printStackTrace();        
            }
            if(info.equals("bye")){
                client.shutDown();    
            }
            tf.setText("");
            tf.requestFocus();        
        }    
    }

    class MyClientReader extends Thread{
        private ChatClient client;
        public MyClientReader(ChatClient client){
            this.client = client;    
        }
        public void run(){
            String info;
            DataInputStream dis = client.getDataInputStream();
            TextArea ta = client.getTextArea();
            try{
                while(client.getRunnable()){
                    info = dis.readUTF();
                    System.out.println("Client=====>"+info);
                    ta.append(info + "\n");
                }        
            }catch (IOException e) {
            }    
        }    


  • 相关阅读:
    paraview添加vector
    origin横纵坐标颠倒
    [转] python提取计算结果的最大最小值及其坐标
    康奈尔大学CFD课程
    anaconda多环境配置
    mfix的Negative gas density报错解决
    python基础补漏-01
    ssh 公钥登陆的问题
    多进程
    关于GIL
  • 原文地址:https://www.cnblogs.com/lee0oo0/p/2470126.html
Copyright © 2011-2022 走看看