Chat_12

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class ChatClient extends Frame {
	Socket socket = null;
	DataOutputStream dOutputStream = null;
	DataInputStream dInputStream = null;
	private boolean bConnected = false;

	TextField tField = new TextField();
	TextArea tContent = new TextArea();

	Thread tRecv = new Thread(new RecvTread());

	public static void main(String[] args) {
		new ChatClient().launchFrame();
	}

	public void launchFrame() {
		this.setLocation(400, 300);
		this.setSize(300, 300);

		add(tField, BorderLayout.SOUTH);
		add(tContent, BorderLayout.NORTH);
		pack();
		this.addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent e) {
				disConnect();
				System.exit(0);
			}
		});
		tField.addActionListener(new TextFieldListener());
		this.setVisible(true);

		connect();

		tRecv.start();
	}

	public void connect() {
		try {
			socket = new Socket("127.0.0.1", 8888);
			dOutputStream = new DataOutputStream(socket.getOutputStream());
			dInputStream = new DataInputStream(socket.getInputStream());
			bConnected = true;
			System.out.println("connected");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void disConnect() {
		try {
			dOutputStream.close();
			dInputStream.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		/*
		 * try { bConnected = false; tRecv.join(); }catch (InterruptedException
		 * e) { e.printStackTrace(); } finally{ try { dOutputStream.close();
		 * dInputStream.close(); socket.close(); } catch (IOException e) {
		 * e.printStackTrace(); } }
		 */
	}

	private class TextFieldListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			String str = tField.getText().trim();
			// tContent.setText(str);
			tField.setText("");

			try {
				dOutputStream.writeUTF(str);
				dOutputStream.flush();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	private class RecvTread implements Runnable {
		public void run() {
			try {
				while (bConnected) {
					String str = dInputStream.readUTF();
					tContent.setText(tContent.getText() + str + "\n");
				}
			} catch (SocketException e) {
				System.out.println("退出");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

你可能感兴趣的:(Chat_12)