?? multiserver.java
字號:
import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class MultiServer
{
static Vector ss=new Vector();
static TextArea text;
static Frame f;
static Panel p,p1,p2;
static Label la;
static TextField file,te;
static Button b;
static int i=0;
static ServerSocket serverSocket;
MultiServer(){
f=new Frame("Socket 服務端");
f.addWindowListener(new window());
f.setSize(400,400);
f.add("North",p=new Panel());
p.setLayout(new GridLayout());
p.add(la=new Label("在線人數",Label.CENTER));
p.add(p1=new Panel());
p1.setLayout(new GridLayout());
p1.add(file=new TextField());
file.setEditable(false);
f.add("Center",text=new TextArea());
f.add("South",p2=new Panel());
p2.setLayout(new GridLayout());
p2.add(te=new TextField("服務器的問候!"));
te.addActionListener(new Myaction());
p2.add(b=new Button("發送"));
b.addActionListener(new Myaction());
text.setEditable(false);
f.setVisible(true);
}
class window extends WindowAdapter
{
public void windowClosing(WindowEvent e){
try{
print("服務器已關閉!!!");
serverSocket.close();
}catch(Exception ee){}
System.exit(-1);}
};
class Myaction implements ActionListener
{
public void actionPerformed(ActionEvent e){
String s="來自服務器的問候:"+te.getText();
try{
print(s);
}catch(Exception ee){}
te.setText(null);
}
};
public void print(String s)throws Exception
{
Socket socket=null;
PrintWriter pw=null;
for(int i=0;i<ss.size();i++)
{
socket=(Socket)ss.get(i);
pw=new PrintWriter(socket.getOutputStream());
pw.println(s);
pw.flush();
}
}
public static void main(String[] args)
{
MultiServer mu=new MultiServer();
boolean flags=true;
try{
serverSocket=new ServerSocket(5555);
}catch(Exception e){
System.out.println("Could not listen on port:4700.");
System.exit(-1);
}
while(flags){
try{
Socket socket=serverSocket.accept();
ss.addElement(socket);
text.append("有一個用戶連接!\n");
if(socket!=null){
AddThread t=new AddThread(mu,socket);
i++;
file.setText(Integer.toString(i));
}
}catch(Exception e){}
}
try{
serverSocket.close();
}catch (Exception e){}
}
}
class AddThread extends Thread
{
BufferedReader br;
MultiServer mu;
Socket socket;
public AddThread(MultiServer mu,Socket socket){
try{
this.mu=mu;
this.socket=socket;
while(true){
br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
start();}
}catch(Exception e){}
}
public void run(){
String line=null;
try{
line=br.readLine();
while(line!=null){
mu.text.append(line+"\n");
if(line.equals("exit")){
mu.i--;
mu.file.setText(Integer.toString(mu.i));
mu.ss.remove(socket);
socket.close();
}
else if(line.startsWith("來自服務器的問候:")){
mu.print("系統提示:"+"來自服務器的問候"+"~~請務盜用服務器名~~");
mu.ss.remove(socket);
socket.close();
}
else mu.print(line);
line=br.readLine();
}
}catch(Exception e){}
}
};
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -