Chat_9

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 {

	public static void main(String[] args) {
		boolean bStarted = false;
		ServerSocket serverSocket = null;
		Socket socket = null;
		DataInputStream dInputStream = null;

		try {
			serverSocket = new ServerSocket(8888);
		}catch (BindException e) {
			System.out.println("端口使用中...");
		} 
		catch (IOException e) {
			e.printStackTrace();
		}

		try {
			bStarted = true;
			while (bStarted) {
				boolean bConnected = false;

				socket = serverSocket.accept();
System.out.println("a client connected!");
				bConnected = true;

				dInputStream = new DataInputStream(socket.getInputStream());

				while (bConnected) {
					String str = dInputStream.readUTF();
System.out.println(str);
				}
				//dInputStream.close();
			}
		}catch (EOFException e) {
			System.out.print("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_9)