日期:2014-05-20 浏览次数:20833 次
package ex30; import javax.swing.*; import java.awt.*; import java.io.*; import java.net.*; import java.util.Date; import java.awt.event.*; public class Ex30_12Server extends JFrame{ private JTextArea jtaDisplay = new JTextArea(); private JTextArea jtaServer = new JTextArea(); private PrintWriter output; private BufferedReader in; private String sendMessage = ""; public static void main(String[] args) { // TODO 自动生成方法存根 new Ex30_12Server(); } public Ex30_12Server(){ setLayout(new GridLayout(2, 1, 5, 5)); jtaDisplay.setEditable(false); jtaDisplay.setBorder(BorderFactory.createTitledBorder( "Server to Client")); jtaServer.setBorder(BorderFactory.createTitledBorder( "Server")); add(new JScrollPane(jtaDisplay)); add(new JScrollPane(jtaServer)); setTitle("Ex30_12Server"); setSize(500, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); try{ ServerSocket serverSocket = new ServerSocket(8000); while(true){ MutiUser mu = new MutiUser(serverSocket.accept()); mu.start(); } } catch(Exception ex){ System.err.print(ex); } jtaServer.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { System.out.println("空白"); if (e.getKeyCode() == KeyEvent.VK_ENTER) { System.out.println("空白"); sendMessage = jtaServer.getText(); System.out.println(sendMessage); jtaServer.setText(""); if(!sendMessage.isEmpty()){ System.out.println(sendMessage); output.println(sendMessage); output.flush(); } else{ System.out.println("空白"); } } } }); } // Define the thread class for send message class SendTask implements Runnable{ private Socket socket; public SendTask(Socket socket){ this.socket = socket; } public void run(){ while(true){ InetAddress inetAddress = socket.getInetAddress(); if(!sendMessage.isEmpty()){ jtaDisplay.append(inetAddress.getHostName() + "\t" + new Date() + "\n"); jtaDisplay.append(sendMessage + "\n"); sendMessage = ""; } } } } // Define the thread class for receive message class ReceiveTask implements Runnable{ private Socket socket; public ReceiveTask(Socket socket){ this.socket = socket; } public void run(){ try{ while(true){ String receiveMessage = in.readLine(); if(!receiveMessage.isEmpty()){ InetAddress inetAddress = socket.getInetAddress(); jtaDisplay.append(inetAddress.getHostName() + "\t" + new Date() + "\n"); jtaDisplay.append(receiveMessage + "\n"); } } } catch(IOException ex){ System.err.println(ex); } } } // 为实现多人聊天,设计的线程类 class MutiUser extends Thread{ private Socket client; public MutiUser(Socket client){ this.client = client; } public void run(){ try{ output = new PrintWriter(client.getOutputStream()); in = new BufferedReader(new InputStreamReader(client.getInputStream())); new Thread(new SendTask(client)).start(); new Thread(new ReceiveTask(client)).start(); } catch(Exception ex){ System.err.println(ex); } } } }