Chat_10

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {
	boolean bStarted = false;
	ServerSocket serverSocket = null;
	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();
			
				//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;
		
		public Client(Socket s) {
			this.socket = s;
			
			try {
				dInputStream = new DataInputStream(s.getInputStream());
				bConnected = true;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void run() {
			try {
				while (bConnected) {
					String str = dInputStream.readUTF();
System.out.println(str);
				}
			} catch (EOFException e) {
				System.out.println("Client clossed!");
			}
			catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if(dInputStream != null)dInputStream.close();
					if(socket !=null)socket.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
}

你可能感兴趣的:(Chat_10)