?? chatserver.java
字號:
// 僠儍僢僩僒乕僶ChatServer.java
// 偙偺僾儘僌儔儉偼,僠儍僢僩偺僒乕僶僾儘僌儔儉偱偡
// 巊偄曽java ChatServer [億乕僩斣崋]
// 億乕僩斣崋傪徣棯偡傞偲,億乕僩斣崋6000 斣傪巊偄傑偡
// 婲摦偺椺java ChatServer
// 廔椆偵偼僐儞僩儘乕儖C 傪擖椡偟偰偔偩偝偄
// 偙偺僒乕僶傊偺愙懕偵偼Telnet.java側偳傪巊偭偰偔偩偝偄
// 愙懕傪巭傔偨偄偲偒偵偼,峴摢偱quit偲擖椡偟偰偔偩偝偄
// 儔僀僽儔儕偺棙梡
import java.io.*;
import java.net.*;
import java.util.*;
// ChatServer僋儔僗
public class ChatServer {
static final int DEFAULT_PORT = 6000;//億乕僩斣崋徣棯帪偼6000 斣傪巊偄傑偡
static ServerSocket serverSocket;
static Vector connections;
// sendAll儊僜僢僪
// 奺僋儔僀傾儞僩偵儊僢僙乕僕傪憲傝傑偡
public static void sendAll(String s){
if (connections != null){// 僐僱僋僔儑儞偑偁傟偽幚峴偟傑偡
for (Enumeration e = connections.elements();
e.hasMoreElements() ;) {
try {
PrintWriter pw = new PrintWriter((
(Socket) e.nextElement()).getOutputStream());
pw.println(s);
pw.flush();
}catch (IOException ex){}
}
}
System.out.println(s);
}
// addConnection儊僜僢僪
// 僋儔僀傾儞僩偲偺愙懕傪捛壛偟傑偡
public static void addConnection(Socket s){
if (connections == null){
connections = new Vector();
}
connections.addElement(s);
}
// deleteConnection儊僜僢僪
// 偁傞僋儔僀傾儞僩偲偺僐僱僋僔儑儞傪嶍彍偟傑偡
public static void deleteConnection(Socket s){
if (connections != null){
connections.removeElement(s);
}
}
// main儊僜僢僪
// 僒乕僶僜働僢僩傪嶌傝,僋儔僀傾儞僩偐傜偺愙懕傪懸偪庴偗傑偡
public static void main(String[] arg){
int port = DEFAULT_PORT ;
if (arg.length > 0) port = Integer.parseInt(arg[0]) ;
try {
serverSocket = new ServerSocket(port);
}catch (IOException e){
System.err.println(e);
System.exit(1);
}
while (true) {
try {
Socket cs = serverSocket.accept();
addConnection(cs);
Thread ct = new Thread(new clientProc(cs));
ct.start();
}catch (IOException e){
System.err.println(e);
}
}
}
}
// clientProc僋儔僗
// 僋儔僀傾儞僩張棟梡僗儗僢僪偺傂側宍偱偡
class clientProc implements Runnable {
Socket s;
BufferedReader in;
PrintWriter out;
String name = null;
ChatServer server = null ;
//僐儞僗僩儔僋僞
public clientProc(Socket s) throws IOException {
this.s = s;
in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
out = new PrintWriter(s.getOutputStream());
}
// 僗儗僢僪偺杮懱
// 奺僋儔僀傾儞僩偲偺愙懕張棟傪峴偄傑偡
public void run(){
try {
while (name == null){
out.print("偍柤慜偼丠: ");
out.flush();
name = in.readLine();
}
String line = in.readLine();
while (!"quit".equals(line)){
ChatServer.sendAll(name + "> " +line);
line = in.readLine();
}
ChatServer.deleteConnection(s);
s.close();
}catch (IOException e){
try {
s.close();
}catch (IOException e2){}
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -