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

📄 chatserver.java

📁 JAVA写的聊天器 能在居于望内多人聊天
💻 JAVA
字号:
import java.net.*;
import java.util.*;
import java.io.*;

public class ChatServer {
	
	ServerSocket ss = null;
	boolean started = false;
	
	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 e) {
				System.out.println("端口使用中....");
				System.out.println("请关掉相关程序并重新运行服务器!");
				System.exit(0);
			} catch(IOException e) {
				e.printStackTrace();
			}
			

			try {
				
				while(started) {
					Socket s = ss.accept();
					Client c = new Client(s);
	System.out.println("有客户端连接上来!");
					new Thread(c).start();
					clients.add(c);
					//dis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					ss.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	class Client implements Runnable {
		private Socket s;
		private DataInputStream dd = null;
		private DataOutputStream dos = null;
		private boolean bConnected = false;
		
		public Client(Socket s) {
			this.s = s;
			try {
				dd = new DataInputStream(s.getInputStream());
				dos = new DataOutputStream(s.getOutputStream());
				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 = dd.readUTF();
					System.out.println(str);
					for(int i=0; i<clients.size(); i++) {
						Client c = clients.get(i);
						c.send(str);
					}	
				}	
			} catch (EOFException e) {
				System.out.println("客户端关闭!");
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if(dd != null) dd.close();
					if(s != null) s.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		
		
		
	}
	
	
}

⌨️ 快捷键说明

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