📄 servthread.java
字号:
package simplechatserver;import java.net.*;import javax.swing.*;import javax.swing.text.*;import java.util.*;/** * Title: 网络聊天程序的服务器端 * Description: * Copyright: Copyright (c) 2001 * Company: * @author * @version 1.0 */public class servThread extends Thread { private int servPort; private ServerSocket servSocket; private JComboBox clientList; private JTextComponent outText; private Vector clients=new Vector(); private boolean running=true; public servThread(int port) { servPort=port; try{ servSocket=new ServerSocket(port); }catch(Exception e){ } } public void setClientList(JComboBox cboComponent){ clientList=cboComponent; } public void setOutTextComponent(JTextComponent component){ outText=component; } public void run(){ try{ int count=0; while(running){ Socket newSocket=servSocket.accept(); count++; String name="Client"+count; ChatSocket chat=new ChatSocket(name,newSocket); chat.setOutTextComponent(outText); chat.setParent(this); chat.connect(); clientList.addItem(name); clients.add(chat); synchronized(this){ outText.setText(outText.getText()+"接受客户端"+name+"的请求\n"); } } }catch(Exception e){ System.out.println(e); } } public boolean send(String msg,String clientName){ try{ Enumeration temp=clients.elements(); ChatSocket chat=null; while(temp.hasMoreElements() ){ chat=(ChatSocket)temp.nextElement(); if(chat.getName().equals(clientName)) break; } if(chat==null) { temp=null; return false; }else{ return(chat.send(msg)); } }catch(Exception e){ return false; } } public synchronized void removeChat(ChatSocket chat){ try{ clientList.removeItem(chat.getName()); if(clients.contains(chat)) clients.remove(chat); synchronized(this){ outText.setText(outText.getText()+"关闭客户端"+chat.getName()+"\n"); } chat=null; }catch(Exception e){ System.out.println(e); } } public void stopServer(){ try{ Enumeration temp=clients.elements(); ChatSocket chat=null; while(temp.hasMoreElements() ){ chat=(ChatSocket)temp.nextElement(); chat.close(); chat=null; } running=false; }catch(Exception e){ } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -