一个多线程聊天室,服务器发不了信息

shijunxing 发布于 2012/11/08 15:29
阅读 353
收藏 0

服务器

package dier;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

 

  @SuppressWarnings("serial")
 public class ChatServer extends JFrame {

   private JPanel p= new JPanel();
      private JTextField jtf1 = new JTextField();
      private DataOutputStream toserver ;//
      private JButton button  = new JButton("发送");
      private static JTextArea jta = new JTextArea();

      private ServerSocket server;
      private static List<Socket> list = new ArrayList<Socket>();
      private ExecutorService exec;//线程池
      private int threadNomber;
   public ChatServer(){

    p.setLayout(new BorderLayout()); 
       JPanel p2 = new JPanel();
       p2.setLayout(new BorderLayout()); 
       p2.add(jtf1,BorderLayout.CENTER);
       p2.add(button,BorderLayout.EAST);
       p.add(p2,BorderLayout.SOUTH);
       p.add(jta,BorderLayout.CENTER);
      
       this.setTitle("聊天室服务器端");
       this.add(p);
       this.setSize(500,300);
       this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口退出
       this.setVisible(true);
       button.addActionListener(new buttonListener1());;
   
    try{
       server = new ServerSocket(3838);
       exec = Executors.newCachedThreadPool();//缓存型池子,先查看池中
           //有没有以前建立的线程,如果有,就reuse.如果没有,就建一个新的线程加入池中


       jta.setText("服务器已经启动\n");
       Socket client = null;//这是要与客户端连接的socket
  
      while(true){
      
    client =server.accept();//等待客户端连接
    threadNomber++;
    jta.setText("已有"+threadNomber+"个客户端接连\n");
       list.add(client);//一有连接就加入列表中
       exec.execute(new Task(client));//将一个实现了Runnable类型的类的实
                       //例作为参数传入execute方法并执行,那么线程就相应的执行了

      }
   }
     catch(Exception e){
    
     e.printStackTrace();
   }
}
    private class buttonListener1 implements ActionListener{

       public void actionPerformed(ActionEvent e) {
          
             String str = jtf1.getText().toString();//把编辑框内容转化为字符串
            
         try {
          while(true){
         
           if(str.equals("end"))
                break;
           else
          toserver.writeUTF(str);//以与机器无关方式使用 UTF-8 修改版编码将一个字符串写入基础输出流
             jta.append("jtf1.getText()");
          toserver.flush();//清空数据输出流
             jtf1.setText("");//清空编辑框
           }
         }
         catch (UnknownHostException e1) {
           
             e1.printStackTrace();
           }
         catch (IOException e1) {
          
             e1.printStackTrace();
          }
     }
 
  }
static class Task implements Runnable{
     
         private Socket client;
            private DataInputStream fromclient;
            private DataOutputStream toclient;
            String msg;
     
 public Task(Socket client) throws IOException{
          
        
         this.client = client;
            fromclient = new DataInputStream(client.getInputStream());//获取输入流
     }
    public void run() {
     BufferedReader br = new BufferedReader(
          new InputStreamReader(System.in));
      try{
        while((msg=fromclient.readUTF())!=null){//从客户端获取数据
            msg = "["+client.getPort()+"]说:"+msg;//客户端的端口作为名字
            jta.append(msg+"\n");//在文本框显示
            String str = br.readLine();
            jta.append("服务器:\n"+str+"\n");
             
            if(str.equals("end"))
             break;
            else
             
            sendMessage();//自定义一个发送方法
          }
        }
      catch(Exception e){
     
         e.printStackTrace();
        }
    }
   public void sendMessage() throws IOException{

    for(Socket client:list){//for循环进行遍历
      
     toclient= new DataOutputStream(client.getOutputStream());//获取输出流
           toclient.writeUTF(msg);//将信息写入流中
      }
    }
  }
   public static void main(String[] args){
           new ChatServer();
   }

 }

 客户端

 

package dier;


import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;


@SuppressWarnings("serial")
public class ChatClient extends JFrame{
 
     private JPanel p= new JPanel();
        private JTextField jtf1 = new JTextField();
        private JTextArea jta1 = new JTextArea();
        private DataOutputStream toserver ;//
        private DataInputStream fromserver;//
        private JButton button  = new JButton("发送");
 
 // private Socket client =null;
   public ChatClient(){
      
       p.setLayout(new BorderLayout()); 
        JPanel p2 = new JPanel();
        p2.setLayout(new BorderLayout()); 
        p2.add(jtf1,BorderLayout.CENTER);
        p2.add(button,BorderLayout.EAST);
        p.add(p2,BorderLayout.SOUTH);
        p.add(jta1,BorderLayout.CENTER);
       
        this.setTitle("聊天室客户端");
        this.add(p);
        this.setSize(500,300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口退出
        this.setVisible(true);
        button.addActionListener(new buttonListener());
 
      try {
 
        Socket client = new Socket("localhost",3838);//绑定socket
        toserver = new DataOutputStream(client.getOutputStream());//数据输出
        fromserver = new DataInputStream(client.getInputStream());//数据接受
   
      while(true){
      //该方法读取使用 UTF-8 修改版格式编码的 Unicode
      //字符串的表示形式;然后以 String 的形式返回此字符串。
       String msg =fromserver.readUTF();
        if(msg!=null)
        jta1.append(msg+"\n");//显示从服务器端传过来的数据
       }
     }
      catch (UnknownHostException e) {
       
       e.printStackTrace();
       }
      catch (IOException e) {
      
       e.printStackTrace();
       }
   }
   private class buttonListener implements ActionListener{

        public void actionPerformed(ActionEvent e) {
           
           String str = jtf1.getText().toString();//把编辑框内容转化为字符串
             
          try {

              toserver.writeUTF(str);//以与机器无关方式使用 UTF-8 修改版编码将一个字符串写入基础输出流
              toserver.flush();//清空数据输出流
              jtf1.setText("");//清空编辑框
            }
          catch (UnknownHostException e1) {
            
           e1.printStackTrace();
            }
          catch (IOException e1) {
           
           e1.printStackTrace();
           }
      }
  
   }
public static void main(String[] args) {
  
     new ChatClient();

 }

}

 

加载中
0
西昆仑
西昆仑
代码,用排版工具~
0
洲宝
洲宝

代码看的egg hurts

返回顶部
顶部