⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 myserver.java

📁 一个在线聊天系统
💻 JAVA
字号:
import java.net.*;
import java.util.*;
import java.text.*;
import java.io.*;
public class myserver {
	static final int PORT=6000;
	static ServerSocket ss;
	static Vector connections;//定义向量放置对话信息
//	static Vector clients;
	
	public static void sendAll(String s){//发送消息
		if (connections != null){
			for (Enumeration e = connections.elements();
					e.hasMoreElements();) {
				try {
					PrintWriter pw = new PrintWriter((
					 (Socket) e.nextElement()).getOutputStream());
					pw.println(s);
					pw.flush();
				}catch (IOException ex){}
			}
		}
		System.out.println(s);
	}
	public static void addConnection(Socket s,ClientProc1 cp){
		if (connections == null){
			connections = new Vector();
		}
		connections.addElement(s);//往向量中添加从客户端传来的对话


	}

	public static void deleteConnection(Socket s,ClientProc1 cp) throws IOException {
		if (connections != null){
			connections.removeElement(s);
			s.close();
		}

	}

	public  static void  main(String [] args){
		
		int port = PORT ;
		try {
			ss = new ServerSocket(port);
			System.out.println("服务器已经启动,正在监听...");
		}catch (IOException e){
			System.err.println(e);
			System.exit(1);
		}
		while (true) {
			try {
				Socket cs = ss.accept();//开始监听客户端
				
				ClientProc1 cp = new ClientProc1(cs);
				//创建线程,向每个客户端发送信息
				Thread ct = new Thread(cp);
				ct.start();

				addConnection(cs,cp);
			}catch (IOException e){
				System.err.println(e);
			}
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -