* 处理窗口关闭事件
*/
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
exitActionPerformed(null);
}
}
/**
* 刷新聊天室,不断刷新clientProcessors,制造最新的用户列表
*/
public static void notifyRoomPeople(){
StringBuffer people = new StringBuffer(Constants.PEOPLE_IDENTIFER);
for (int i = 0; iclientProcessors.size(); i++) {
ClientProcessor c = (ClientProcessor) clientProcessors.elementAt(i);
people.append(Constants.SEPERATOR).append(c.clientName);
}
// 用sendClients方法向客户端发送用户列表的信息
sendMsgToClients(people);
}
/**
* 向所有客户端群发消息
* @param msg
*/
public static synchronized void sendMsgToClients(StringBuffer msg) {
for (int i = 0; iclientProcessors.size(); i++) {
ClientProcessor c = (ClientProcessor) clientProcessors.elementAt(i);
System.out.println("send msg: " + msg);
c.send(msg);
}
}
/**
* 关闭所有连接
*/
public static void closeAll(){
while (clientProcessors.size()0) {
ClientProcessor c = (ClientProcessor) clientProcessors.firstElement();
try {
// 关闭socket连接和处理线程
c.socket.close();
c.toStop();
} catch (IOException e) {
System.out.println("Error:" + e);
} finally {
clientProcessors.removeElement(c);
}
}
}
/**
* 判断客户端是否合法 。
* 不允许同一客户端重复登陆,所谓同一客户端是指IP和名字都相同 。
* @param newclient
* @return
*/
public static boolean checkClient(ClientProcessor newclient){
if (clientProcessors.contains(newclient)){
return false;
} else {
return true;
}
}
/**
* 断开某个连接,并且从连接列表中删除
* @param client
*/
public static void disconnect(ClientProcessor client){
disconnect(client, true);
}
/**
* 断开某个连接 , 根据要求决定是否从连接列表中删除
* @param client
* @param toRemoveFromList
*/
public static synchronized void disconnect(ClientProcessor client, boolean toRemoveFromList){
try {
//在服务器端程序的list框中显示断开信息
connectInfoList.add(client.clientIP + "断开连接");
ChatServer.activeConnects--; //将连接数减1
String constr = "目前有" + ChatServer.activeConnects + "客户相连";
statusBar.setText(constr);
//向客户发送断开连接信息
client.send(new StringBuffer(Constants.QUIT_IDENTIFER));
client.socket.close();
} catch (IOException e) {
System.out.println("Error:" + e);
} finally {
//从clients数组中删除此客户的相关socket等信息,并停止线程 。
if (toRemoveFromList) {
clientProcessors.removeElement(client);
client.toStop();
}
}
}
public static void main(String[] args) {
ChatServer chatServer1 = new ChatServer();
chatServer1.setVisible(true);
System.out.println("Server starting ...");
ServerSocket server = null;
try {
// 服务器端开始侦听
server = new ServerSocket(Constants.SERVER_PORT);
} catch (IOException e) {
System.out.println("Error:" + e);
System.exit(1);
}
while (true) {
// 如果当前客户端数小于MAX_CLIENT个时接受连接请求
【java五子棋代码解析 java五子棋的简单思路】if (clientProcessors.size()Constants.MAX_CLIENT) {
Socket socket = null;
try {
// 收到客户端的请求
socket = server.accept();
if (socket != null) {
System.out.println(socket + "连接");
推荐阅读
- 虎牙直播年龄,虎牙直播最低年龄
- 金大班全集下载,金大班24集全集播放
- 换电脑怎么选固态硬盘格式,更换电脑固态硬盘
- 数据库设计文论php 数据库设计怎么写
- 联想显卡温度怎么看多少,联想电脑怎么看显卡温度
- phpcms中的pc标签,cms标签教程
- 不用登录注册恋爱游戏下载,不用登录的女生恋爱游戏
- c语言函数名前有引用符号 c语言中调用函数
- 鸿蒙系统米家,鸿蒙和米家啥区别