首页 新闻 会员 周边 捐助

Java写的一个简易的多客户聊天程序 用户发送信息后不停抛出EOFException

0
悬赏园豆:30 [已关闭问题] 关闭于 2015-12-14 21:04
 1 //MessengerServer.java
 2 
 3 
 4 import java.util.*;
 5 import java.net.*;
 6 import java.io.*;
 7 
 8 public class MessengerServer {
 9     public void startServer(){
10         try{
11             ServerSocket serverSocket = new ServerSocket(8000, 100);
12             System.out.println("服务器已启动...");
13             
14             while(true){
15                 Socket clientSocket = serverSocket.accept();
16                 
17                 System.out.println("已接收到客户来自:" +clientSocket.getInetAddress());
18                 
19                 ChatHandler handler = new ChatHandler(clientSocket);
20                 handler.start();
21             }
22             
23         }catch(IOException ioException){
24             ioException.printStackTrace();
25         }
26     }
27     
28     public static void main(String[] args){
29         MessengerServer application = new MessengerServer();
30         application.startServer();
31     }
32 }
 1 //ChatHandler.java
 2 
 3 import java.io.*;
 4 import java.net.*;
 5 import java.util.*;
 6 
 7 public class ChatHandler implements Runnable{
 8     
 9     protected Socket socket;
10     protected ObjectInputStream dataIn;
11     protected ObjectOutputStream dataOut;
12     protected Thread listener;
13     protected static Vector handlers = new Vector();
14     private boolean keepListening = true;
15     
16     public ChatHandler (Socket socket){
17         this.socket = socket;
18     }
19     
20     public synchronized void start(){
21         if(listener == null){
22             try{
23                 dataIn = new ObjectInputStream(socket.getInputStream());
24                 dataOut = new ObjectOutputStream(socket.getOutputStream());
25                 
26                 listener = new Thread(this);
27                 listener.start();
28             }catch(IOException ioException){
29                 ioException.printStackTrace();
30             }
31         }
32     }
33     
34     public synchronized void stop(){
35         if(listener != null){
36             try{
37                 if(listener != Thread.currentThread())
38                     listener.interrupt();
39                 listener = null;
40                 dataOut.close();
41                 socket.close();
42             }catch(IOException ignored){
43             }
44         }
45     }
46     
47     public void run(){
48         String message = "";
49         try{
50             handlers.addElement(this);
51             while(keepListening){
52                 message = (String)dataIn.readObject();
53                 
54                 if(message.equals("DISCONNECT")){
55                     dataOut.writeObject(message);
56                     dataOut.flush();
57                     stopListening();
58                 }else
59                     broadcast(message);
60             }
61         }catch(ClassNotFoundException classNotFoundException){
62         
63         }catch(EOFException ignored){
64         
65         }catch(IOException ex){
66             if(listener == Thread.currentThread())
67                 ex.printStackTrace();
68         }finally{
69             handlers.removeElement(this);
70         }
71         
72         try{
73             dataIn.close();
74         }catch(IOException ioException){
75             ioException.printStackTrace();
76         }
77         
78         stop();
79     }
80     
81     protected void broadcast(String message){
82         synchronized (handlers){
83             Enumeration enumer = handlers.elements();
84             while(enumer.hasMoreElements()){
85                 ChatHandler handler = (ChatHandler)enumer.nextElement();
86                 try{
87                     handler.dataOut.writeObject(message);
88                     handler.dataOut.flush();
89                 }catch(IOException ex){
90                     handler.stop();
91                 }
92             }
93         }
94     }
95     
96     public void stopListening(){
97         keepListening = false;
98     }
99 }//end class ChatHandler
  1 //MessengerClient
  2 
  3 import java.io.*;
  4 import java.net.*;
  5 import java.awt.*;
  6 import java.awt.event.*;
  7 import javax.swing.*;
  8 import javax.swing.border.*;
  9 
 10 
 11 public class MessengerClient extends JFrame implements Runnable{
 12 
 13     private JTextArea messageArea;
 14     private JTextArea inputArea;
 15     
 16     private JButton connectButton;
 17     private JButton disconnectButton;
 18     private JButton sendButton;
 19     private JLabel statusBar;
 20     
 21     private String userName;
 22     private String chatServer;
 23     private ObjectOutputStream output;
 24     private ObjectInputStream input;
 25     
 26     private Socket client;
 27     private boolean connected;
 28     private Thread processConnection;
 29     
 30     public MessengerClient(String host){
 31         super("聊天客户端");
 32         chatServer = host;
 33         
 34         connectButton = new JButton("登陆");
 35         connectButton.setEnabled(true);
 36         ActionListener connectListener = new ConnectListener();
 37         connectButton.addActionListener(connectListener);
 38         //代码1 //创建登陆按钮并设置事件侦听器
 39         
 40         disconnectButton = new JButton("退出");
 41         disconnectButton.setEnabled(false);
 42         ActionListener disconnectListener = new DisconnectListener();
 43         disconnectButton.addActionListener(disconnectListener);
 44         
 45         messageArea = new JTextArea();
 46         messageArea.setEditable(false);
 47         messageArea.setWrapStyleWord(true);
 48         messageArea.setLineWrap(true);
 49         
 50         JPanel messagePanel = new JPanel();
 51         messagePanel.setLayout(new BorderLayout(10, 10));
 52         messagePanel.add(new JScrollPane(messageArea), BorderLayout.CENTER);
 53         
 54         inputArea = new JTextArea(4, 20);
 55         inputArea.setWrapStyleWord(true);
 56         inputArea.setLineWrap(true);
 57         inputArea.setEditable(false);
 58         
 59         sendButton = new JButton("发送");
 60         sendButton.setEnabled(false);
 61         sendButton.addActionListener(
 62             new ActionListener(){
 63                 public void actionPerformed(ActionEvent event){
 64                     sendMessage(userName + ">" + inputArea.getText());
 65                     inputArea.setText("");
 66                 }
 67             });
 68         
 69         JPanel buttonPanel = new JPanel();
 70         buttonPanel.setLayout(new GridLayout(3, 1));
 71         buttonPanel.add(sendButton);
 72         buttonPanel.add(connectButton);
 73         buttonPanel.add(disconnectButton);
 74         
 75         Box box = new Box(BoxLayout.X_AXIS);
 76         box.add(new JScrollPane(inputArea));
 77         box.add(buttonPanel);
 78         
 79         messagePanel.add(box, BorderLayout.SOUTH);
 80         
 81         statusBar = new JLabel("离线");
 82         statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED));
 83         
 84         Container container = getContentPane();
 85         
 86         container.add(messagePanel, BorderLayout.CENTER);
 87         container.add(statusBar, BorderLayout.SOUTH);
 88         
 89         addWindowListener(
 90             new WindowAdapter(){
 91                 public void windowClosing(WindowEvent event){
 92                     if(connected){
 93                         sendMessage("DISCOUNNECT");
 94                         do{
 95                         }while(connected);
 96                     }
 97                     System.exit(0);
 98                 }
 99             });
100         
101     }
102     
103     public void sendMessage(String message){
104         try{
105             output.writeUTF(message); //代码2 //发送message到output对象
106             output.flush();
107         }catch(IOException ioException){
108             ioException.printStackTrace();
109         }
110     }
111     
112     public void run(){
113         String message = "";
114         do{
115             try{
116                 message = (String)input.readObject();
117             }catch(ClassNotFoundException classNotFoundException){
118                 displayMessage("\n收到异常对象类型");
119             }catch(EOFException eofException){
120                 System.err.println("连接终止");
121             }catch(IOException ioException){
122                 ioException.printStackTrace();
123             }
124             if(message.equals("DISCONNECT")){
125                 try{
126                     input.close(); //代码3 //关闭输入输出流
127                     client.close();
128                 }catch(IOException ioException){
129                     ioException.printStackTrace();
130                 }
131                 connected = false;
132             }else
133                 displayMessage(message + "\n");
134         }while(connected);
135     }
136     
137     private class ConnectListener implements ActionListener{
138         public void actionPerformed(ActionEvent event){
139             try{
140                 client = new Socket(chatServer, 8000);
141                 output = new ObjectOutputStream(client.getOutputStream());
142                 output.flush();
143                 input = new ObjectInputStream(client.getInputStream()) ;//代码4  //创建对象输入流
144             }catch(IOException ioException){
145                 ioException.printStackTrace();
146             }
147             userName = JOptionPane.showInputDialog(null, "请输入用户名");  //使用JOptionPane弹出输入对话框
148     
149             messageArea.setText("");
150             connectButton.setEnabled(false);
151             disconnectButton.setEnabled(true);
152             
153             sendButton.setEnabled(true);
154             inputArea.setEditable(true);
155             inputArea.requestFocus();
156             statusBar.setText("在线:"  + userName);
157             connected = true;
158             
159             processConnection = new Thread(MessengerClient.this);
160             processConnection.start();
161         }
162     }
163     
164     private class DisconnectListener implements ActionListener{
165         public void actionPerformed(ActionEvent event){
166             sendMessage("DISCOUNNECT");
167             
168             sendButton.setEnabled(false);
169             disconnectButton.setEnabled(false);
170             
171             inputArea.setEditable(false);
172             connectButton.setEnabled(true);
173             
174             statusBar.setText("离线");
175         }
176     }
177     
178     private void displayMessage(final String messageToDisplay){
179         SwingUtilities.invokeLater(
180             new Runnable(){
181                 public void run(){
182                     messageArea.append(messageToDisplay);
183                     messageArea.setCaretPosition(
184                             messageArea.getText().length() );
185                 }
186             }
187         );
188     }
189     public static void main(String[] args) {
190         MessengerClient application;
191         
192         if(args.length == 0)
193             application = new MessengerClient("127.0.0.1");
194         else
195             application = new MessengerClient( args[0]);
196         
197         application.setSize(300, 400);
198         application.setResizable(false);
199         application.setVisible(true);
200 
201     }
202 
203 }

只有以上3个文件,当我登入一个用户,发送任意信息(数字或字符或空白)都会不停地输出“连接终止”,如下图:

 

我觉得是MessengerClient.java第120行抛出异常输出的结果,不知该如何解决

SharpeyeKardel的主页 SharpeyeKardel | 初学一级 | 园豆:30
提问于:2015-12-05 12:39
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册