📄 chatroomserver.java
字号:
//服务器端程序
import java.net.*;
import java.io.*;
import java.util.*;
public class ChatRoomServer {
public static ArrayList<TcpThread> cl = new ArrayList<TcpThread>();
public static void main(String args[]) {
ServerSocket ss = null;
Socket socket = null;
try {
ss = new ServerSocket(3000);
while (true) {
socket = ss.accept();
TcpThread crc = new TcpThread(socket);
cl.add(crc);
crc.start();
System.out.println(socket.getInetAddress() + " " + cl.size());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (socket != null)
socket.close();
if (ss != null)
ss.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class TcpThread extends Thread {
private Socket socket;
public static String data;
BufferedReader br = null;
PrintWriter pw = null;
InputStream is = null;
InputStreamReader isr = null;
OutputStream os = null;
public TcpThread(Socket socket) {
this.socket = socket;
}
public void sendMess() {
pw.println(data);
}
public void run() {
try {
is = socket.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
os = socket.getOutputStream();
pw = new PrintWriter(os, true);
data = "Welcome!: " + socket.getInetAddress();
for (Object ss : ChatRoomServer.cl)
((TcpThread) ss).sendMess();
while (true) {
data = br.readLine();
if (data == null)
break;
else if (data != null) {
System.out.println(data);
for (TcpThread ss : ChatRoomServer.cl)
ss.sendMess();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (pw != null)
pw.close();
if (socket != null)
socket.close();
ChatRoomServer.cl.remove(this);
System.out.println(socket.getInetAddress().toString()
+ "client quit\n" + "linkings:"
+ ChatRoomServer.cl.size());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -