📄 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();
}
public void start(){
try {
ss = new ServerSocket(8888);
started=true;
}catch (BindException e){
System.out.println("端口被占用中……");
System.out.println("请关掉相关程序并重新运行程序 !");
System.exit(0);
}
catch(IOException e){
e.printStackTrace();
}
try{
while(started){
Socket s = ss.accept();
Client c=new Client(s);
System.out.println("a client accept!");
clients.add(c);
new Thread(c).start();
}
}catch (IOException e) {
try {
ss.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
class Client implements Runnable{
private Socket s;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean bConnected = false;
public Client(Socket s){
this.s = s;
try{
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnected = true;
} catch(IOException e){
e.printStackTrace();
}
}
public void run() {
try{
while(bConnected){
String str = dis.readUTF();
System.out.println(str);
for(int i = 0; i < clients.size(); i++) {
Client c = clients.get(i);
c.send(str);
}
}
} catch (IOException e) {
try {
s.close();
dis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
//e.printStackTrace();
System.out.println("client closed !");
}
}
public void send(String str) {
try {
dos.writeUTF(str);
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -