📄 chatserver.java
字号:
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
DataInputStream dis = null;
boolean started = false;
ServerSocket ss = null;
Socket s = 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 be){
System.out.println("Port is used");
System.exit(0);
}catch(IOException e){
e.printStackTrace();
}
try{
while(started){
s = ss.accept();
System.out.println("A client connected!");
Client c = new Client(s);
clients.add(c);
new Thread(c).start();
}
}catch(IOException e){
e.printStackTrace();
}finally{
try {
if(ss != null) ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Client implements Runnable{
Socket s = null;
DataInputStream dis = null;
DataOutputStream dos = null;
boolean bConnected = false;
public Client(Socket s){
this.s = s;
try{
dis = new DataInputStream(this.s.getInputStream());
dos = new DataOutputStream(this.s.getOutputStream());
bConnected = true;
}catch(IOException ioe){
ioe.printStackTrace();
}
}
public void send(String str){
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this);
}
}
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(EOFException eo){
System.out.println("client closed");
}catch(IOException e){
e.printStackTrace();
}finally{
try {
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 + -