网络编程作业聊天室代码

合集下载
相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。


package name.zrl;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import .ServerSocket;
import .Socket;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

/**
* 聊天室服务器端
* @author Administrator
*/
@SuppressWarnings("serial")
public class ChatServer extends JFrame {
JPanel jp = new JPanel();
JButton jbStart = new JButton("启动服务器");
JLabel jl = new JLabel("服务器的监听端口为8000");
JList list = new JList();
JScrollPane jsp = new JScrollPane(list);
//——————–
private ServerSocket serverSocket;
Vector listData = new Vector();
private boolean started = false;
ArrayList clients = new ArrayList();

public ChatServer() {
jp.add(jl);
jp.add(jbStart);
add(jp,BorderLayout.NORTH);
add(jsp);

jbStart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
startServer(e);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(150,150,400,400);
setVisible(true);
}

//启动服务器
public void startServer(ActionEvent e) {
if(!started) {
try {
serverSocket = new ServerSocket(8000);
listData.clear();
listData.add(String.format("%tF %> 服务器启动成功,在8000端口监听…");
list.setListData(listData);
started = true;
jbStart.setText("停止服务器");
new Thread(new Runnable(){
public void run() {
while(! serverSocket.isClosed()) {
try {
Socket socket = serverSocket.accept(); //不停的接收请求
ChatThread client = new ChatThread(socket,ChatServer.this);
clients.add(client); //保存客户端
client.start(); //启动线程
listData.add(String.format("%tF %> " + socket.getInetAddress().getHostAddress() + "进入聊天室");
list.setListData(listData);
} catch (IOException e) {


//e.printStackTrace();
break;
}
}
}
}).start();
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
stopServer();
}

}

public void sendMessage(String msg) {
for(ChatThread client : clients) {
client.sendMessage(msg);
}
}

public static void main(String[] args) {
new ChatServer();
}


public void removeClient(ChatThread client) {
clients.remove(client);
listData.add(String.format("%tF %> " + client.getName() + "退出聊天室");
list.setListData(listData);
client.release();
}

public void stopServer() {
for(ChatThread client : clients) {
client.release();
}

if(serverSocket != null && ! serverSocket.isClosed()) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
listData.add(String.format("%tF %> 服务器停止…");
list.setListData(listData);
jbStart.setText("启动服务器");
started = false;
}
}

相关文档
最新文档