JFrame是一个顶层的框架类,好比一个窗户的框子。也是一个容器类。这个框子可以嵌入几个玻璃窗。
JPanel是一个容器类,相当于一大玻璃窗。
JLabel等是一些基础组件,它必须置于某个容器里,类似于窗花、剪纸,必须置于窗户的表面。
public class Server extends JFrame implements Runnable{
private Socket s = null;
private ServerSocket ss = null;
private JTextField jtf = new JTextField();
private JTextArea jta = new JTextArea();
private ArrayList<ChatThread>clients = new ArrayList<ChatThread>();
public Server() throws Exception{
this.setTitle("服务器端");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(jta,BorderLayout.CENTER);
jta.setBackground(Color.yellow);
this.setSize(400,200);
this.setVisible(true);
ss = new ServerSocket(9999);
new Thread(this).start();
}
public void run(){
try{
while(true){
s = ss.accept();
ChatThread ct = new ChatThread(s);
clients.add(ct);
ct.start();
}
}catch (Exception ex){
ex.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(this,"游戏异常退出!");
System.exit(0);
}
}
class ChatThread extends Thread{
private Socket s = null;
private BufferedReader br = null;
private PrintStream ps = null;
private boolean canRun = true;
public ChatThread(Socket s)throws Exception{
this.s = s;
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
ps = new PrintStream(s.getOutputStream());
}
public void run(){
try{
while (canRun){
String str = br.readLine();
sendMessage(str);
}
}catch (Exception ex){
canRun = false;
clients.remove(this);
}
}
}
public void sendMessage(String msg){
for(ChatThread ct:clients){
ct.ps.println(msg);
}
}
public static void main(String[] args)throws Exception{
Server server = new Server();
}
}
这里写代码片