📄 server.java
字号:
import java.io.*;import java.net.*;import java.util.Vector;import javax.swing.JOptionPane;public class Server { public String get_client_name; private ServerSocket serverSocket = null; public static int port = 60000; private boolean listening = true; Vector clientSockets = new Vector(10); String s = JOptionPane.showInputDialog(null,"请输入用户数目"); int n =Integer.parseInt(s); public Server(String get_client_name) {this.get_client_name= get_client_name; } public Server() throws IOException { try { serverSocket = new ServerSocket(port); } catch (Exception ex) { System.err.println("不能监听端口:" + port); ex.printStackTrace(System.err); System.exit(-1); } System.out.println("成功监听端口:" + port); while (listening) if(clientSockets.size()<n) //n为事先启动服务时设定好的上限人数 addClient(serverSocket.accept()); serverSocket.close(); } public void addClient(Socket socket) throws IOException { //if(clientSockets.size()<2) //{ new ServerThread(socket, this).start(); clientSockets.add(socket); // send("聊天室共有 " + clientSockets.size() + " 人");}//} public void removeClient(Socket socket,int i) { try{ if(i==2)send("欢送某人的离去\n"+ "聊天室还有" + clientSockets.size() + " 人"); clientSockets.remove(socket); } catch(SocketException ex){ JOptionPane.showMessageDialog(null,"it is not normol exit"); } catch(IOException ex){ JOptionPane.showMessageDialog(null,"it is not normol exit"); } } public void send(String msg) throws IOException { Socket socket = null; for (int I = 0; I < clientSockets.size(); I++) { socket = (Socket)(clientSockets.get(I)); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println(msg); } } public static void main(String[] args) throws IOException { new Server(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -