?? chatserver.java
字號(hào):
import java.net.*;
import java.util.*;
import java.io.*;
public class ChatServer {
ServerSocket ss = null;
boolean started = false;
List<Client> clients = new ArrayList<Client>();
public static void main(String[] args) {
new ChatServer().start();
}
public void start() {
try {
ss = new ServerSocket(8888);
started = true;
}catch(BindException e) {
System.out.println("端口使用中....");
System.out.println("請(qǐng)關(guān)掉相關(guān)程序并重新運(yùn)行服務(wù)器!");
System.exit(0);
} catch(IOException e) {
e.printStackTrace();
}
try {
while(started) {
Socket s = ss.accept();
Client c = new Client(s);
System.out.println("有客戶端連接上來!");
new Thread(c).start();
clients.add(c);
//dis.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Client implements Runnable {
private Socket s;
private DataInputStream dd = null;
private DataOutputStream dos = null;
private boolean bConnected = false;
public Client(Socket s) {
this.s = s;
try {
dd = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this);
System.out.println("對(duì)方退出了!我從List里面去掉了!");
}
}
public void run() {
try {
while(bConnected) {
String str = dd.readUTF();
System.out.println(str);
for(int i=0; i<clients.size(); i++) {
Client c = clients.get(i);
c.send(str);
}
}
} catch (EOFException e) {
System.out.println("客戶端關(guān)閉!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(dd != null) dd.close();
if(s != null) s.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -