package text;

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().start1();

	}

	public void start1() {
		try {
			ss = new ServerSocket(8888);
			started = true;
		} catch (BindException e) {
			System.out.println("端口使用中-----请关闭相关socket");
			System.exit(0);

		} catch (IOException e) {
			System.out.println("监听失败--可能原因服务器启动失败");
		}
		try {

			while (started) {

				Socket s = ss.accept();
				Client c = new Client(s);
				new Thread(c).start();
				clients.add(c);
			}
		} 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 bconnection = false;

		public Client(Socket s) {
			this.s = s;
			try {
				dis = new DataInputStream(s.getInputStream());
				dos = new DataOutputStream(s.getOutputStream());
				bconnection = true;

			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void send(String str) {
			try {
				dos.writeUTF(str);
			} catch (IOException e) {
				clients.remove(this);
				System.out.println("对方退出了,我从内存去掉了");
			}
		}

		public void run() {
			//Client c = null;
			try {
				while (bconnection) {

					String str = dis.readUTF();
					System.out.println(str);
					/*
					 * for(Iterator<Client> it =
					 * clients.iterator();it.hasNext();){ Client c = it.next();
					 * c.send(str);//需要锁定,故不采用 }
					 */
					for (int i = 0; i < clients.size(); i++) {
						Client c = clients.get(i);
						c.send(str);
					}

				}
			}

			catch (EOFException e) {
				System.out.println("Client close!!!");
			}

			catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (dis != null)
						dis.close();
					if (dos != null)
						dos.close();
					if (s != null)
						s.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}

		}
	}
}
最近下载更多
zeng1206  LV5 2023年12月28日
Oriamphei  LV1 2023年11月23日
www123ww  LV1 2022年12月13日
heweimin  LV12 2022年7月18日
shan454  LV3 2022年1月24日
胡萝北呀  LV3 2021年11月26日
ComeDebug  LV6 2021年9月6日
datlric  LV1 2021年7月5日
忧麦紫  LV18 2021年6月26日
q啦啦啦a  LV2 2021年3月17日
最近浏览更多
taoshen95  LV14 1月18日
zeng1206  LV5 2023年12月21日
Oriamphei  LV1 2023年11月23日
yangxb2  LV10 2023年7月11日
林间听风  LV10 2023年6月5日
belike 2023年5月26日
暂无贡献等级
另类清晨  LV8 2023年5月15日
CL200228  LV4 2023年5月5日
1721281527  LV2 2023年2月12日
hhdbzz  LV1 2022年12月29日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友