经过几天的努力终于搞定了。(我是个菜鸟还)
虽然是个很简单的程序,到搞定前一直很郁闷,但搞定的那一刻,真的很兴奋,我都大声喊了出来。、
程序代码如下:
package muyizhou.chat;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CServer {
//保存当前处理客户端请求的处理器线程
ArrayList arraylist;
private PrintWriter getWriter(Socket socket) throws IOException{
OutputStream socketOut=socket.getOutputStream();
return new PrintWriter(socketOut,true);
}
private BufferedReader getReader(Socket socket) throws IOException{
InputStream socketIn=socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn));
}
//主方法
public static void main(String args[]){
new CServer().go();
}
public void go(){
arraylist=new ArrayList();
try{
ServerSocket serverSock=new ServerSocket(5000);
while(true){
Socket clientSocket=serverSock.accept();
PrintWriter writer=getWriter(clientSocket);
arraylist.add(writer);
Thread t=new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("got a connect");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
//广播信息
public void tellEveryone(String message){
Iterator it=arraylist.iterator();
while(it.hasNext()){
try{
PrintWriter writer=(PrintWriter) it.next();
writer.println(message);
writer.flush();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
public class ClientHandler implements Runnable{
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSocket){
try{
sock=clientSocket;
reader=getReader(clientSocket);
}catch(IOException ex){
ex.printStackTrace();
}
}
public void run(){
String message;
try{
while((message=reader.readLine())!=null){
System.out.println("read"+message);
tellEveryone(message);
}
}catch(IOException ex){
ex.printStackTrace();
}
}
}
}
package muyizhou.chat;
import java.io.*;
import java.net.Socket;
import java.net.InetAddress;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.StringTokenizer;
import javax.swing.border.TitledBorder;
public class CClient extends JFrame implements ActionListener{
JLabel nameLabel=new JLabel();
JLabel ipLabel=new JLabel();
JTextField nameTextField=new JTextField(15);
JTextField ipTextField=new JTextField(15);
JTextField msgTextField=new JTextField(30);
JButton connectButton=new JButton();
JButton disconnectButton=new JButton();
JTextArea chatContentTextArea=new JTextArea(15,60);
JButton sendMsgButton=new JButton();
JLabel msgLabel=new JLabel();
java.awt.List peopleList=new java.awt.List(15);
Socket socket=null;
PrintWriter pw=null;
ClientListener listener=null;
//构造函数
public CClient(){
init();
}
//图形界面
public void init(){
this.setTitle("聊天室客户端");
//初始化按钮和标签
nameLabel.setText("姓名");
ipLabel.setText("IP");
connectButton.setText("连接");
connectButton.addActionListener(this);
disconnectButton.setText("断开");
disconnectButton.addActionListener(this);
//设置聊天内容不可编辑
chatContentTextArea.setEditable(false);
sendMsgButton.setText("发送");
sendMsgButton.addActionListener(this);
msgTextField.setText("");
//pane1放置输入姓名和连接两个按钮
JPanel panel1=new JPanel();
panel1.setLayout(new FlowLayout());
panel1.add(nameLabel);
panel1.add(nameTextField);
panel1.add(ipLabel);
panel1.add(ipTextField);
panel1.add(connectButton);
panel1.add(disconnectButton);
//用于放置聊天信息显示和聊天人员列表
JPanel panel2=new JPanel();
panel2.setLayout(new FlowLayout());
JScrollPane pane1=new JScrollPane(chatContentTextArea);
pane1.setBorder(new TitledBorder(BorderFactory.createEtchedBorder
(Color.white,new Color(134,134,134)),"聊天内容"));
panel2.add(pane1);
//用于放置发送信息区域
JPanel panel3=new JPanel();
panel3.setLayout(new FlowLayout());
panel3.add(msgLabel);
panel3.add(msgTextField);
panel3.add(sendMsgButton);
//将组件添加到界面
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(panel1,BorderLayout.NORTH);
this.getContentPane().add(panel2, BorderLayout.CENTER);
this.getContentPane().add(panel3, BorderLayout.SOUTH);
this.pack();
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
}catch(Exception e){
e.printStackTrace();
}
}
//得到输出流
private PrintWriter getWriter(Socket socket) throws IOException{
OutputStream socketOut=socket.getOutputStream();
return new PrintWriter(socketOut,true);
}
//得到输入流
private BufferedReader getReader(Socket socket) throws IOException{
InputStream socketIn=socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn));
}
//处理按钮事件
public void actionPerformed(ActionEvent event){
Object source=event.getSource();
if(source==connectButton){
//如果点击连接按钮
if(socket==null){
try{
socket=new Socket(ipTextField.getText(),5000);
System.out.println(socket);
pw=getWriter(socket);
listener=new ClientListener(this,nameTextField.getText(),socket);
listener.start();
}catch(IOException e){
System.out.println("Error:"+e);
disconnect();
}
}
}else if(source==disconnectButton){
disconnect();
}else if(source==sendMsgButton){
String msg=nameTextField.getText()+":"+msgTextField.getText();
pw.println(msg);
pw.flush();
}
}
//断开连接
public void disconnect(){
if(socket!=null){
try{
socket.close();
listener.toStop();
//socket=null;
}catch(IOException e){
System.out.println("Error:"+e);
}
}
}
//主方法
public static void main(String args[]){
CClient client=new CClient();
client.setVisible(true);
}
//客户端线程用来监听服务器传来的 信息
class ClientListener extends Thread{
String name=null;
BufferedReader br=null;
PrintWriter pw=null;
Socket socket=null;
CClient parent=null;
boolean running=true;
//构造方法
public ClientListener(CClient p,String n,Socket s){
//接受参数
parent=p;
name=n;
socket=s;
try{
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
pw=new PrintWriter(s.getOutputStream());
}catch(IOException e){
System.out.println("ERROR:"+e);
parent.disconnect();
}
}
//停止监听
public void toStop(){
this.running=false;
}
//线程运行方法
public void run(){
while(running){
//msg=null;
String msg=null;
try{
//读取从服务器传来的信息
msg=br.readLine();
if(msg!=null){
System.out.println("receive msg:"+msg);
parent.chatContentTextArea.append(msg);
parent.chatContentTextArea.append("/n");
}
}catch(IOException e){
System.out.println("ERROR:"+e);
parent.disconnect();
}
}
}
}
}