java实现C/S模式聊天室(根据马士兵聊天室程序进行优化)

根据马士兵老师聊天室程序进行优化,同时增加聊天者之间的交互。

同时增加服务端会为每一个客户端增加一个交互窗口,让服务器可以和每一个客户端交互!

服务端代码

import java.net.*;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import javax.swing.JFrame;

public class ChatServer extends JFrame {
	JTextArea ta = new JTextArea();
	ServerSocket server = null;
	Collection cClient = new ArrayList();

	public ChatServer(int port) throws Exception {
		server = new ServerSocket(port);
		add(ta, BorderLayout.CENTER);
		setBounds(200, 200, 300, 450);
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		setVisible(true);
	}

	public void startServer() throws Exception {
		while (true) {
			Socket s = server.accept();
			cClient.add(new ClientConn(s));
			ta.append(s.getInetAddress().getHostName() + "进入" + "    " + "端口号"
					+ s.getPort());
			ta.append("\n" + "当前在前总人数: " + cClient.size() + "\n\n");
		}
	}

	class ClientConn extends Frame implements Runnable, ActionListener {
		TextArea ta1 = null;
		TextArea ta2 = null;
		Button btn = null;
		Socket s = null;

		public ClientConn(Socket s) {
			ta1 = new TextArea(3, 30);
			ta2 = new TextArea(2, 15);
			btn = new Button("发送");
			this.setLayout(new BorderLayout());
			this.add(ta1, BorderLayout.CENTER);
			this.add(ta2, BorderLayout.SOUTH);
			this.add(btn, BorderLayout.EAST);
			this.setSize(300, 200);
			this.setVisible(true);
			this.setTitle("" + s.getInetAddress().getHostName() + "端口"
					+ s.getPort());
			this.s = s;
			(new Thread(this)).start();
			btn.addActionListener(this);
		}

		public void actionPerformed(ActionEvent e) {
			try {
				DataOutputStream dos = new DataOutputStream(s.getOutputStream());
				dos.writeUTF("服务器:\n" + ta2.getText() + "\n");
				ta1.append("服务器:\n" + ta2.getText() + "\n");
				ta2.setText("");
			} catch (IOException E) {

			}
		}

		public void send(String str, String st) throws IOException {
			DataOutputStream dos = new DataOutputStream(s.getOutputStream());
			dos.writeUTF(st + "说:\n" + str);
		}

		public void dispose() {
			try {
				// this.setVisible(false);
				super.dispose();
				ta.append(s.getInetAddress().getHostName() + "退出" + "\n");
				if (s != null)
					s.close();
				cClient.remove(this);
				ta.append("当前在线人数: " + cClient.size() + "\n\n");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		public void run() {
			try {

				DataInputStream dis = new DataInputStream(s.getInputStream());
				String str = dis.readUTF();
				String st = s.getInetAddress().getHostName();
				while (str != null && str.length() != 0) {
					for (Iterator it = cClient.iterator(); it.hasNext();) {
						ClientConn cc = (ClientConn) it.next();
						if (this != cc) {
							cc.send(str, st);
						}
					}
					ta1.append(st + "说:\n" + str + "\n");
					str = dis.readUTF();
				}
				this.dispose();
			} catch (Exception e) {
				this.dispose();
			}

		}
	}

	public static void main(String[] args) throws Exception {
		JFrame.setDefaultLookAndFeelDecorated(true);
		ChatServer cs = new ChatServer(8888);
		cs.startServer();
	}
}

 

客户端代码

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import javax.swing.JButton;

public class ChatClient extends JFrame {
	JTextArea ta = new JTextArea("你可以通过此客户端的群聊!" + "\n" + "发送快捷键  ALT+ENTER \n");
	TextArea tf = new TextArea(3, 21);
	JButton btn = new JButton("发送");
	JPanel jp = new JPanel();
	Socket s = null;

	public ChatClient() throws Exception {
		this.setLayout(new BorderLayout(10, 10));
		this.add(ta, BorderLayout.CENTER);
		jp.add(btn, BorderLayout.SOUTH);
		this.add(tf, BorderLayout.SOUTH);
		this.add(jp, BorderLayout.EAST);

		btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				try {
					String sSend = tf.getText();
					if (sSend.trim().length() == 0)
						return;
					ChatClient.this.send(sSend);
					tf.setText("");
					ta.append("你自己说:" + "\n");
					ta.append(sSend + "\n");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		btn.setMnemonic(KeyEvent.VK_ENTER);
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		setBounds(300, 300, 400, 500);
		setVisible(true);
		tf.requestFocus();
		try {
			s = new Socket("10.20.10.201", 8888);
		} catch (Exception e) {
			ta.append("对不起!无法连接服务器" + "\n");
		}
		(new Thread(new ReceiveThread())).start();
	}

	public void send(String str) throws Exception {
		DataOutputStream dos = new DataOutputStream(s.getOutputStream());
		dos.writeUTF(str);
	}

	public void disconnect() throws Exception {
		s.close();
	}

	public static void main(String[] args) throws Exception {
		JFrame.setDefaultLookAndFeelDecorated(true);
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		ChatClient cc = new ChatClient();
		String str = br.readLine();
		while (str != null && str.length() != 0) {
			cc.send(str);
			str = br.readLine();
		}
		cc.disconnect();
	}

	class ReceiveThread implements Runnable {

		public void run() {
			if (s == null)
				return;
			try {
				DataInputStream dis = new DataInputStream(s.getInputStream());
				String str = dis.readUTF();
				while (str != null && str.length() != 0) {

					ChatClient.this.ta.append(str + "\n");
					str = dis.readUTF();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}
}

 

你可能感兴趣的:(java,C++,c,swing,C#)