?? server.java
字號:
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Calendar;
public class Server extends Frame implements ActionListener{
private boolean serving = false;
private Color backGround = new Color(255,255,255);
private String rightNow;
private InetAddress serverAddress;
private ServerSocket server;
private ServerThread st;
private Hashtable userHashTable;
private Hashtable connectHashTable;
private Label serverIP = new Label("本服務器IP地址:");
private TextField printServerIP = new TextField();
private Label serverPort = new Label("端口號:");
private TextField getServerPort = new TextField("1234");
private Button start = new Button(" 啟動服務器 ");
private Button end = new Button(" 停止服務器 ");
private Label outputTitle = new Label("聊天記錄:");
private TextArea output = new TextArea();
private Label user = new Label("在線成員(0)");
private List list = new List();
// 響應關閉按鈕的內部類
private class WindowCloser extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
// 窗口布局
private void openWindow()
{
Font fb = new Font("Helvetica", Font.BOLD, 17);
Font fp = new Font("Courier", Font.PLAIN, 14);
Panel north = new Panel();
north.setLayout(new FlowLayout());
north.add(serverIP);
serverIP.setBackground(backGround);
serverIP.setFont(fp);
north.add(printServerIP);
printServerIP.setBackground(backGround);
north.add(serverPort);
serverPort.setBackground(backGround);
serverPort.setFont(fp);
north.add(getServerPort);
getServerPort.setBackground(backGround);
Panel east = new Panel();
east.setLayout(new BorderLayout());
east.add("North", user);
user.setBackground(backGround);
user.setFont(fp);
east.add("Center", list);
list.setBackground(backGround);
Panel center = new Panel();
center.setLayout(new BorderLayout());
center.add("North", outputTitle);
outputTitle.setBackground(backGround);
outputTitle.setFont(fp);
center.add("Center", output);
output.setBackground(backGround);
Panel south = new Panel();
south.setLayout(new FlowLayout());
south.add(start);
start.setBackground(new Color(192, 192, 192));
start.setFont(fb);
south.add(end);
end.setBackground(new Color(192, 192, 192));
end.setFont(fb);
setLayout(new BorderLayout());
add("North", north);
north.setBackground(backGround);
add("East", east);
east.setBackground(backGround);
add("Center", center);
add("South", south);
setBackground(backGround);
}
// 構造方法
public Server()throws UnknownHostException, IOException
{
super("多人聊天室服務器 Server");
serving = false;
serverAddress = InetAddress.getLocalHost();
byte[] IP = serverAddress.getAddress();
printServerIP.setText((IP[0]&0xFF)+"."+(IP[1]&0xFF)+"."
+(IP[2]&0xFF)+"."+(IP[3]&0xFF));
printServerIP.setEditable(false);
output.setEditable(false);
start.addActionListener(this);
end.addActionListener(this);
end.setEnabled(false);
addWindowListener(new WindowCloser());
openWindow();
pack();
setSize(500, 550);
show();
}
// 用于接收客戶消息的線程類
private class ServerThreadSingle extends Thread{
public Socket connection;
private DataInputStream in;
private DataOutputStream out;
private boolean login;
private String userName;
public ServerThreadSingle(Socket newConnection){
try{
connection = newConnection;
in = new DataInputStream(connection.getInputStream());
out = new DataOutputStream(connection.getOutputStream());
login = false;
userName = new String("");
start();
}catch(IOException ioe){
output.append("Error: "+ioe);
}
}
public void run(){
try{
String line = new String("Q");
while(!login){
if(!serving) break;
line = in.readUTF();
if(line.charAt(0) == 'L'){
userName = line.substring(2);
if(userName.length() == 0 ||userName.equalsIgnoreCase("請在此處輸入您的名字")){
out.writeUTF("R"); //refused
break;
}
// 判斷是否已存在該用戶名
for(Enumeration e =userHashTable.keys(); e.hasMoreElements();){
String str = (String)(e.nextElement());
if(str.equalsIgnoreCase(userName)){
out.writeUTF("R"); //refused
return;
}
}
// 向登陸的用戶發送當前在線用戶列表
login = true;
list.add(userName);
user.setText("在線成員 ("+list.getItemCount()+")");
String[] str = list.getItems();
line = "A "; //accepted
for (int i = 0; i < str.length; i ++){
line += (str [i] + " ");
}
out.writeUTF(line);
line = "L "+userName;
rightNow = Calendar.getInstance().getTime().toLocaleString();
output.append(rightNow+"\n!!!"+userName+" 上線.\n\n");
// 向在線用戶(不包括當前客戶)發送消息
for(Enumeration e =userHashTable.elements(); e.hasMoreElements();){
DataOutputStream out = (DataOutputStream)(e.nextElement());
out.writeUTF(line);
}
userHashTable.put(userName, out); // 將登錄的客戶加入名單
connectHashTable.put(userName, connection);
}
}
//當用戶退出時,該用戶從名單中剔除
while(login){
line = in.readUTF();
if(!serving) break;
if(line.charAt(0) == 'Q'){
out.writeUTF("Q");
login = false;
userHashTable.remove(userName);
connectHashTable.remove(userName);
list.remove(userName);
user.setText("在線成員 ("+list.getItemCount()+")");
line = "Q "+userName;
}
else{
line = userName+" 對大家說:\n"+line.substring(2);
}
rightNow = Calendar.getInstance().getTime().toLocaleString();
output.append(rightNow+"\n"+(line.charAt(0)=='Q'?"!!!"+userName+"剛剛下線.":line)+"\n\n");
// 向所有客戶發送消息
for(Enumeration e =userHashTable.elements(); e.hasMoreElements();){
DataOutputStream out = (DataOutputStream)(e.nextElement());
out.writeUTF(line);
}
}
in.close();
out.close();
connection.close();
}catch(SocketException se){
userHashTable.remove(userName);
connectHashTable.remove(connection);
list.remove(userName);
output.append("!!!與 "+userName+" 斷開連接\n");
}catch(IOException ioe){
if(!(ioe instanceof EOFException)){
output.append("Error: "+ioe+"\n\n");
}
}
}
}
// 用于接受客戶連接請求的線程類
private class ServerThread extends Thread{
private boolean running;
public ServerThread()
{
start();
}
public void run()
{
try{
while(serving){
Socket connection = server.accept();
ServerThreadSingle handler
= new ServerThreadSingle(connection);
}
}catch(SocketException se){
rightNow = Calendar.getInstance().getTime().toLocaleString();
output.append(rightNow+"\n!!!服務器停止.\n\n");
}catch(IOException ioe){
output.append("Error: "+ioe+"\n\n");
}
}
}
// 消息處理方法
public void actionPerformed(ActionEvent event){
if(event.getSource() == end && serving) {
try{
for(Enumeration e =userHashTable.elements(); e.hasMoreElements();){
DataOutputStream out = (DataOutputStream)(e.nextElement());
out.writeUTF("Q");
}
serving = false;
userHashTable.clear();
connectHashTable.clear();
list.clear();
user.setText("在線成員 (0)");
server.close();
end.setEnabled(false);
start.setEnabled(true);
}catch(SocketException se){
rightNow = Calendar.getInstance().getTime().toLocaleString();
output.append(rightNow+"\n!!!服務器停止運行.\n\n");
}catch(IOException ioe){
output.append("Error: "+ioe+"\n\n");
}
}
else if(event.getSource() == start && !serving){
try{
server = new ServerSocket(Integer.parseInt(getServerPort.getText()));
rightNow = Calendar.getInstance().getTime().toLocaleString();
output.append(rightNow+"\n!!!服務器啟動.\n\n");
start.setEnabled(false);
end.setEnabled(true);
userHashTable = new Hashtable();
connectHashTable = new Hashtable();
st = new ServerThread();
serving = true;
}catch(IOException ioe){
output.append("Error: "+ioe+"\n\n");
}
}
}
// 程序入口
public static void main(String args [])throws UnknownHostException, IOException
{
Server s = new Server();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -