Chat_11

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ChatServer {
	boolean bStarted = false;
	ServerSocket serverSocket = null;

	List<Client> clients = new ArrayList<Client>();

	public static void main(String[] args) {
		new ChatServer().start();
	}

	public void start() {
		try {
			serverSocket = new ServerSocket(8888);
			bStarted = true;
		} catch (BindException e) {
			System.out.println("端口使用中...");
			System.out.println("请关闭相关程序再运行服务器!");
			System.exit(0);
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			while (bStarted) {

				Socket socket = serverSocket.accept();
				Client client = new Client(socket);
				System.out.println("a client connected!");

				new Thread(client).start();
				clients.add(client);
				// dInputStream.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				serverSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	class Client implements Runnable {
		private Socket socket;
		private DataInputStream dInputStream = null;
		private boolean bConnected = false;
		private DataOutputStream dOutputStream = null;

		public Client(Socket s) {
			this.socket = s;

			try {
				dInputStream = new DataInputStream(s.getInputStream());
				dOutputStream = new DataOutputStream(s.getOutputStream());
				bConnected = true;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void sent(String str) {
			try {
				dOutputStream.writeUTF(str);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void run() {
			try {
				while (bConnected) {
					String str = dInputStream.readUTF();
					System.out.println(str);
					for (int i = 0; i < clients.size(); i++) {
						Client client = clients.get(i);
						client.sent(str);
					}
				}
			} catch (EOFException e) {
				System.out.println("Client clossed!");
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (dInputStream != null)
						dInputStream.close();
					if (dOutputStream != null)
						dOutputStream.close();
					if (socket != null)
						socket.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
}

你可能感兴趣的:(Chat_11)