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

📄 chatserver.java

📁 Java实现的聊天程序
💻 JAVA
字号:
import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer {
	boolean started = false; //判断变量,服务器端是否启动
	ServerSocket ss = null;
	
	List<Client> clients = new ArrayList<Client>(); //集合对象用于收集每个客服端的连接
	
	public static void main(String[] args) {
		new ChatServer().start();
	}
	public void start() {   //细节的隐藏和包装,main中内部类,不可以用于其他类来访问
		try {	
			ss = new ServerSocket(8888); //tcp协议
			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("a client connected");
				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 dis = null;
		private DataOutputStream dos = null;	//得到输出流
		private boolean bConnected = false;
		
		public Client(Socket s) {
			this.s = s;
			try {
				dis = new DataInputStream( s.getInputStream());		//初始化dis	
				dos = new DataOutputStream(s.getOutputStream());	//初始化dos
				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里面去掉了!");
					//e.printStackTrace();
					
				}
		}
		
		public void run() {
			try {
				while(bConnected) {	//死循环,只要有就读数据
					String str = dis.readUTF(); //读utp
System.out.println(str); //输入,便于调试
				for(int i=0; i<clients.size(); i++) {
					Client c = clients.get(i);
					c.send(str);
				}
				
				/*   效率不高,会进行锁定
				for(Iterator<Client> it = clients.iterator(); it.hasNext();) {
					Client c = it.next();
					c.send(str);
				}*/
				/*
				Iterator<Client> it = clients.iterator();
				while(it.hasNext()) {
					Client c = it.next();
					c.send(str);
				}*/
				  
				}
			} catch (EOFException e) {
				System.out.println("Client closed!");
			} catch (IOException e) {	
				e.printStackTrace(); // 打印其他异常	
			} finally {
				try {
					if(dis != null) dis.close();
					if(dos != null) dos.close();
					if(s != null) {
						s.close();
						//s = null; 
					}
				} catch (IOException e1) { 
					e1.printStackTrace();
				}

			}
		}
	}	
	
}

⌨️ 快捷键说明

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