⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 framechatserver.java

📁 《Java程序设计与应用》-张仕斌-源程序 《Java程序设计与应用》-张仕斌-源程序
💻 JAVA
字号:
//FrameChatServer.java
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FrameChatServer extends JFrame implements Runnable{
	private JTextField txtPort = null;      //服务器端口
	private JButton btnStart = null;        //启动监听服务
	private JButton btnStop = null;         //停止服务
	private JTextArea txtLog = null;        //登录和登出日志
	private Thread srvThread = null;        //服务器线程
	private ServerSocket server = null;     //ServerSocket对象
	private ThreadSocket [] clients = null;  //客户服务线程
	private int LISTEN_PORT ;              
	
	/*这里定义了客户服务线程内部类*/
	class ThreadSocket extends Thread {
		private FrameChatServer server = null;  //服务器对象
		private Socket s = null;                //会话Socket
		public String name = null;              //当前会话客户名称
		DataOutputStream out = null;            //数据输出流
		BufferedReader in = null;               //数据输入流
		
		public ThreadSocket(FrameChatServer server , Socket s) {
			this.server = server;
			this.s = s;
		}
		
		public void run() {   //主线程
			while (s != null)   //当前Socket不为空时
			try {
				in = new BufferedReader(new InputStreamReader(s.getInputStream()));
				out = new DataOutputStream(s.getOutputStream());
				String str = null;
				name = in.readLine();   //客户端先发送名称
				server.addUser(name);   //在服务器端注册一个用户
				str = in.readLine();    //继续读取客户端发送的聊天信息
				while(!str.equals("Quit")) {  //如果发送Quit则退出
					server.addChat(name + " : " + str);   //向所有用户转发
					str = in.readLine();   //继续读取下一信息
				}
				server.delUser(name);    //在服务器端注销一个用户
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
		
		public void sendMsg(String msg) { //发送消息
			try {
				out.writeBytes(msg + "\n");
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
		
		public void close() {   //关闭连接
			try {
				in.close();
				s.close();
				server = null;
				s = null;
			}catch(IOException e) {}
		}
	}	
	/*内部类定义结束*/
	
	public FrameChatServer() {  //服务器构造函数
		super("聊天服务器");
		
		txtPort = new JTextField(6);
		btnStart = new JButton("启动");
		btnStop = new JButton("停止");
		
		txtLog = new JTextArea(8,35);
		
		Container cp = this.getContentPane();
		
		Panel p = new Panel();
		p.setLayout(new FlowLayout(FlowLayout.LEFT));
		p.add(new JLabel("端口:"));
		p.add(txtPort);
		p.add(btnStart);
		p.add(btnStop);
		cp.add(p,BorderLayout.NORTH);
		
		p = new Panel();
		p.setLayout(new FlowLayout(FlowLayout.LEFT));
		p.add(new JLabel("日志:"));
		JScrollPane sp = new JScrollPane(txtLog);  //可滚动的日志
		txtLog.setEditable(false);
		p.add(sp);		
		cp.add(p , BorderLayout.CENTER);
		
		btnStart.addActionListener(new ActionListener() {  //启动按钮
			public void actionPerformed(ActionEvent e) {
				start();
			}
		});
		
		btnStop.addActionListener(new ActionListener() {   //停止按钮
			public void actionPerformed(ActionEvent e) {
				stop();
			}
		});
	}
	
	public void run() {   //服务器监听主线程
		Thread cur = Thread.currentThread();  //取得当前线程
		while (cur == srvThread) {   //如果是服务器监听线程
			try {
				Socket ts = server.accept();    //接收一个请求
				int i;
				for( i = 0; i < clients.length ; i++) {
					if (clients[i] == null) {   //查找一个空闲服务线程
						clients[i] = new ThreadSocket(this , ts); //创建服务进程
						clients[i].start();    //启动服务进程
						break;
					}
				}
				if (i >= clients.length) {   //如果没有空闲进程
					ts.close();               //关闭这个连接
					ts = null;
				}
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void start() {   //启动服务器监听服务
		try {
			LISTEN_PORT = Integer.parseInt(txtPort.getText());
			server = new ServerSocket(LISTEN_PORT); //创建服务器套接字
			clients = new ThreadSocket[20];       //创建服务队列
			txtLog.append("服务器监听于端口:" + LISTEN_PORT + "\n");
		}catch(Exception e) {
			JOptionPane.showMessageDialog(this , e.toString() ,
			                     "错误" , JOptionPane.PLAIN_MESSAGE);
			return;
		}
		srvThread = new Thread(this);   //创建服务器线程
		srvThread.start();       //启动服务
	}
	
	public void stop() {  //停止服务
		if (srvThread == null) {
			JOptionPane.showMessageDialog(this , "服务器未启动!" ,
			                     "错误" , JOptionPane.PLAIN_MESSAGE);
			return;
		}
		try {
			srvThread = null;  //结束当前线程
			for (int i = 0 ; i < clients.length ; i++) { //释放服务进程
				if (clients[i] != null) {
					clients[i].close();
					clients[i] = null;
				}
			}
			clients = null;
			server.close();  //关闭服务器套接字
			server = null;
			txtLog.append("服务器停止!\n");
		}catch(IOException e) {
			txtLog.append("服务器停止错误!\n");
			e.printStackTrace();
		}
	}
	
	public void addUser(String name) {  //在服务器上注册一个用户
		String str = "User[" + name + "]Joined,Welcome!";
		txtLog.append(str + "\n");
		try {
			for (int i = 0 ; i < clients.length ; i++) {
				if (clients[i] != null) {  //向所有用户广播
					clients[i].sendMsg(str);
				}
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public void delUser(String name) {  //在服务器上删除注销一个用户
		String str = "User[" + name + "] has been exited!";
		txtLog.append(str + "\n");
		for (int i = 0 ; i < clients.length ; i++) {
			if (clients[i] != null) {
				clients[i].sendMsg(str);     //向所有用户广播
				if (clients[i].name.equals(name)) {  //如果是当前用户退出
					clients[i].close();
					clients[i] = null;
				}
			}
		}
	}
	
	public void addChat(String chat) {  //向所有用户广播聊天信息
		for (int i = 0 ; i < clients.length ; i ++) {
			if (clients[i] != null) {
				clients[i].sendMsg(chat);
			}
		}
	}
	
	public static void main(String[]args) {
		FrameChatServer fcs = new FrameChatServer();		
		fcs.setSize(400,240);
		fcs.setResizable(false);
		fcs.setDefaultCloseOperation(EXIT_ON_CLOSE);
		fcs.setVisible(true);
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -