📄 chatserver.java
字号:
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
boolean started = false;
ServerSocket ss = null;
List clients = new ArrayList();
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) {
boolean bConnected = false;
Socket s = ss.accept();
// 当接收到客户端的链接后,各个客户启动自己的一个线程
Client c = new Client(s);
System.out.println("a client connected!");
new Thread(c).start();
clients.add(c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// if(ss != null)
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 代表的是客户端在服务器端的一个包装
class Client implements Runnable {
// 每个客服都要有自己的链接
private Socket s;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean bConnected = true;
public Client(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
// 一旦连上了,就设置为true,开始服务,不停的读
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("对方退出了,我从List里面退出了");
}
}
public void run() {
try {
while (bConnected) {
String str = dis.readUTF();
System.out.println(str);
// 只要一接收到每个client端的信息就马上转发给其他的client
for (int i = 0; i < clients.size(); i++) {
Client c = (Client) clients.get(i);
c.send(str);
}
/*
* 下面的两个循环都可以代替上面的循环,但是程序内部会 for(Iterator it =
* clients.iterator();it.hasNext();) { Client c = (Client)
* it.next(); c.send(); }
*/
/*
* Iterator it = clients.iterator(); while(it.hasNext()) {
* Client c = (Client) it.next(); c.send(); }
*/
}
} catch (EOFException e) {
System.out.println("Client Close!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (dis != null)
dis.close();
if (dos != null)
dos.close();
if (s != null)
s.close();// 如果客户端断掉了,则要马上把Socket关掉,否则会出错
// s = null;
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new ChatServer().start();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -