java聊天程序源码

一.客户端程序,有窗口,可以输入、显示所有人发的信息

;   
  1.   
  2. import java.awt.BorderLayout;   
  3. import java.awt.Button;   
  4. import java.awt.TextArea;   
  5. import java.awt.TextField;   
  6. import java.awt.event.ActionEvent;   
  7. import java.awt.event.ActionListener;   
  8. import java.io.BufferedReader;   
  9. import java.io.IOException;   
  10. import java.io.InputStreamReader;   
  11. import java.io.PrintStream;   
  12. import java.net.Socket;   
  13. import java.net.UnknownHostException;   
  14. import javax.swing.JFrame;   
  15.   
  16. @SuppressWarnings("serial")   
  17. public class Client extends JFrame {   
  18.     TextArea textArea = new TextArea();// 创建一个文本域   
  19.     TextField textField = new TextField();// 创建一个文本框   
  20.   
  21.     Button button_send = new Button("发送");   
  22.     Button button_clear = new Button("清屏");   
  23.   
  24.     static Socket clientLink;   
  25.     BufferedReader br;   
  26.     PrintStream ps;   
  27.     String msg;   
  28.     StringBuffer sb = new StringBuffer();   
  29.   
  30.     static {   
  31.         try {   
  32.             clientLink = new Socket("127.0.0.1",8888);   
  33.         } catch (UnknownHostException e) {   
  34.             e.printStackTrace();   
  35.         } catch (IOException e) {   
  36.             e.printStackTrace();   
  37.         }   
  38.     }   
  39.   
  40.     public Client() {   
  41.         super("客户端");   
  42.     }   
  43.   
  44.     public void runClient() {   
  45.         this.setLocation(400450);   
  46.         this.setSize(400400);   
  47.         this.add(textArea, BorderLayout.NORTH);// 把文本添加到窗体中   
  48.         this.add(textField, BorderLayout.SOUTH);// 把文本框添加到窗体中   
  49.         this.add(button_send, BorderLayout.EAST);// 把按钮添加到窗体中   
  50.         this.add(button_clear, BorderLayout.WEST);   
  51.         this.setVisible(true);// 窗体是否可见   
  52.         this.pack();// 自动调整布局   
  53.         textField.setText("请输入信息");   
  54.   
  55.         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
  56.   
  57.         try {   
  58.   
  59.             br = new BufferedReader(new InputStreamReader(clientLink   
  60.                     .getInputStream()));   
  61.             ps = new PrintStream(clientLink.getOutputStream());   
  62.   
  63.             // 发送按钮事件   
  64.             button_send.addActionListener(new ActionListener() {   
  65.                 @Override  
  66.                 public void actionPerformed(ActionEvent e) {   
  67.                     msg = textField.getText();   
  68.                     System.out.println(msg);   
  69.                     // 这里不能用缓冲流,向服务器发送信息   
  70.                     ps.println(msg);   
  71.                     ps.flush();   
  72.                 }   
  73.   
  74.             });   
  75.   
  76.             // 回车时,文本域事件   
  77.             textField.addActionListener(new ActionListener() {   
  78.                 @Override  
  79.                 public void actionPerformed(ActionEvent e) {   
  80.                     msg = textField.getText();   
  81.                     // 这里不能用缓冲流写   
  82.                     ps.println(msg);   
  83.                     ps.flush();   
  84.   
  85.                 }   
  86.   
  87.             });   
  88.   
  89.             // 清屏按钮事件   
  90.             button_clear.addActionListener(new ActionListener() {   
  91.                 @Override  
  92.                 public void actionPerformed(ActionEvent e) {   
  93.                     textArea.setText("");   
  94.                     sb.delete(0, sb.length());   
  95.                 }   
  96.             });   
  97.   
  98.             // 接受服务器信息   
  99.             while (true) {   
  100.                 msg = br.readLine();   
  101.                 sb.append(msg + "\n");   
  102.                 textArea.setText(sb.toString());   
  103.                 textField.setText("");   
  104.             }   
  105.   
  106.         } catch (UnknownHostException e) {   
  107.             e.printStackTrace();   
  108.         } catch (IOException e) {   
  109.             e.printStackTrace();   
  110.         } finally {   
  111.             try {   
  112.                 if (null != clientLink) {   
  113.                     clientLink.close();   
  114.   
  115.                 }   
  116.                 if (null != br) {   
  117.                     br.close();   
  118.                 }   
  119.                 if (null != ps) {   
  120.                     ps.close();   
  121.                 }   
  122.   
  123.             } catch (IOException e) {   
  124.                 e.printStackTrace();   
  125.             }   
  126.         }   
  127.   
  128.     }   
  129.   
  130.     public static void main(String[] args) {   
  131.         new Client().runClient();   
  132.     }   
  133.   
  134. }  
package com.adu.client;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JFrame;

@SuppressWarnings("serial")
public class Client extends JFrame {
	TextArea textArea = new TextArea();// 创建一个文本域
	TextField textField = new TextField();// 创建一个文本框

	Button button_send = new Button("发送");
	Button button_clear = new Button("清屏");

	static Socket clientLink;
	BufferedReader br;
	PrintStream ps;
	String msg;
	StringBuffer sb = new StringBuffer();

	static {
		try {
			clientLink = new Socket("127.0.0.1",8888);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Client() {
		super("客户端");
	}

	public void runClient() {
		this.setLocation(400, 450);
		this.setSize(400, 400);
		this.add(textArea, BorderLayout.NORTH);// 把文本添加到窗体中
		this.add(textField, BorderLayout.SOUTH);// 把文本框添加到窗体中
		this.add(button_send, BorderLayout.EAST);// 把按钮添加到窗体中
		this.add(button_clear, BorderLayout.WEST);
		this.setVisible(true);// 窗体是否可见
		this.pack();// 自动调整布局
		textField.setText("请输入信息");

		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		try {

			br = new BufferedReader(new InputStreamReader(clientLink
					.getInputStream()));
			ps = new PrintStream(clientLink.getOutputStream());

			// 发送按钮事件
			button_send.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					msg = textField.getText();
					System.out.println(msg);
					// 这里不能用缓冲流,向服务器发送信息
					ps.println(msg);
					ps.flush();
				}

			});

			// 回车时,文本域事件
			textField.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					msg = textField.getText();
					// 这里不能用缓冲流写
					ps.println(msg);
					ps.flush();

				}

			});

			// 清屏按钮事件
			button_clear.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					textArea.setText("");
					sb.delete(0, sb.length());
				}
			});

			// 接受服务器信息
			while (true) {
				msg = br.readLine();
				sb.append(msg + "\n");
				textArea.setText(sb.toString());
				textField.setText("");
			}

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != clientLink) {
					clientLink.close();

				}
				if (null != br) {
					br.close();
				}
				if (null != ps) {
					ps.close();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public static void main(String[] args) {
		new Client().runClient();
	}

}


二.服务器端实现了线程的控制,只要启动就可以监听客户端的请求以及发送的消息

Java代码 复制代码 收藏代码
  1. package com.adu.server;   
  2.   
  3. import java.io.IOException;   
  4. import java.net.ServerSocket;   
  5. import java.net.Socket;   
  6. import java.util.ArrayList;   
  7. import java.util.List;   
  8.   
  9. /**  
  10.  * @author GYH  
  11.  *   
  12.  */  
  13. public class Server {   
  14.   
  15.     static ServerSocket server;   
  16.     Socket clientLink;   
  17.     List<Socket> clientLinkList = new ArrayList<Socket>();   
  18.     int count;   
  19.   
  20.     static {   
  21.         try {   
  22.             // 开启服务器   
  23.             server = new ServerSocket(8888);   
  24.             System.out.println("服务器已启动!");   
  25.   
  26.         } catch (IOException e) {   
  27.             e.printStackTrace();   
  28.         }   
  29.     }   
  30.   
  31.     public void runServer() {   
  32.         try {   
  33.             while (true) {   
  34.                 clientLink = server.accept();   
  35.                 System.out.println("连接数:" + (++count));   
  36.                 clientLinkList.add(clientLink);   
  37.                 ServerThread st = new ServerThread(clientLinkList, clientLink);   
  38.                 new Thread(st).start();   
  39.             }   
  40.   
  41.         } catch (IOException e) {   
  42.             e.printStackTrace();   
  43.         }   
  44.   
  45.     }   
  46.   
  47.     public static void main(String[] args) {   
  48.         Server server = new Server();   
  49.         server.runServer();   
  50.   
  51.     }   
  52.   
  53. }  
package com.adu.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * @author GYH
 * 
 */
public class Server {

	static ServerSocket server;
	Socket clientLink;
	List<Socket> clientLinkList = new ArrayList<Socket>();
	int count;

	static {
		try {
			// 开启服务器
			server = new ServerSocket(8888);
			System.out.println("服务器已启动!");

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void runServer() {
		try {
			while (true) {
				clientLink = server.accept();
				System.out.println("连接数:" + (++count));
				clientLinkList.add(clientLink);
				ServerThread st = new ServerThread(clientLinkList, clientLink);
				new Thread(st).start();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		Server server = new Server();
		server.runServer();

	}

}



Java代码 复制代码 收藏代码
  1. package com.adu.server;   
  2.   
  3. import java.io.BufferedReader;   
  4. import java.io.IOException;   
  5. import java.io.InputStreamReader;   
  6. import java.io.PrintStream;   
  7. import java.net.Socket;   
  8. import java.util.List;   
  9.   
  10. public class ServerThread implements Runnable {   
  11.     List<Socket> clientLinkList;   
  12.     Socket clientLink;   
  13.     BufferedReader br;   
  14.     PrintStream ps;   
  15.     String msg;   
  16.     String ip;   
  17.     public ServerThread(List<Socket> clientLinkList, Socket clientLink) {   
  18.         this.clientLinkList = clientLinkList;   
  19.         this.clientLink = clientLink;   
  20.     }   
  21.   
  22.     @Override  
  23.     public void run() {   
  24.   
  25.         try {   
  26.             br = new BufferedReader(new InputStreamReader(clientLink   
  27.                     .getInputStream()));               
  28.             //获得当前用户的IP   
  29.             ip=clientLink.getInetAddress().getHostAddress();   
  30.                
  31.             //把当前用户发来的信息发送给所有用户.   
  32.             while (null != (msg=br.readLine())) {          
  33.                 for (int i = 0; i < clientLinkList.size(); i++) {   
  34.                     ps = new PrintStream(clientLinkList.get(i)   
  35.                             .getOutputStream());   
  36.                     ps.println("IP为:"+ip+"的朋友说:"+msg+"\n");   
  37.                        
  38.                     ps.flush();   
  39.                 }   
  40.             }   
  41.                
  42.                
  43.            
  44.         } catch (IOException e) {   
  45.             e.printStackTrace();   
  46.         }finally{   
  47.             try {   
  48.                 if(null!=clientLink){   
  49.                     clientLink.close();   
  50.                        
  51.                 }   
  52.                 if(null!=br){   
  53.                     br.close();   
  54.                 }   
  55.                 if(null!=ps){   
  56.                     ps.close();   
  57.                 }   
  58.                    
  59.             } catch (IOException e) {   
  60.                 e.printStackTrace();   
  61.             }   
  62.         }   
  63.   
  64.     }   
  65.   
  66. }  
posted @ 2011-09-22 22:36  星月磊子  阅读(1661)  评论(0编辑  收藏  举报