?? chatserver.java
字號:
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
boolean started = false;
ServerSocket ss = null;
List<Client> clients = new ArrayList<Client>();
public static void main(String[] args) {
new ChatServer().start();
}
void start() {
try {
ss = new ServerSocket(8888);
started = true;
} catch (BindException e) {
System.out.println("端口使用中。。。");
System.out.println("請關閉相應程序!");
System.exit(0);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
while (started) {
Socket s;
s = ss.accept();
Client c = new Client(s);
clients.add(c);
new Thread(c).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Client implements Runnable {
private boolean bConnected = false;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private Socket s = null;
Client(Socket s) {
this.s = s;
bConnected = true;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this);
System.out.println("One Client exits!");
}
}
public void run() {
System.out.println("A client connected!");
try {
while (bConnected) {
String str = null;
str = dis.readUTF();
System.out.println(str);
for(int i = 0;i < clients.size();i ++) {
clients.get(i).send(str);
}
}
} catch (EOFException e) {
System.out.println("A client is closed!");
} catch (IOException e) {
System.out.println("Error!");
e.printStackTrace();
} finally {
try {
/*
* 如果dis、s還沒有初始化,就不要關閉它們 所以在關閉前先判斷一下
*/
if (dis != null)
dis.close();
if (dos != null)
dos.close();
if (s != null)
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -