Chat_7

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.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class ChatClient extends Frame{
	Socket socket = null;
	TextField tField = new TextField();
	TextArea tContent = new TextArea();
	
	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) {
				// TODO Auto-generated method stub
				System.exit(0);
			}
			
		});
		tField.addActionListener(new TextFieldListener());
		this.setVisible(true);
		
		connect();
	}
	
	public void connect() {
		try {
			socket = new Socket("127.0.0.1",8888);
System.out.println("connected");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private class TextFieldListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			String str = tField.getText().trim();
			tContent.setText(str);
			tField.setText("");
			
			try {
				DataOutputStream dOutputStream = new DataOutputStream(socket.getOutputStream());
				dOutputStream.writeUTF(str);
				dOutputStream.flush();
				dOutputStream.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		
	}
}


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


public class ChatServer {

	public static void main(String[] args) {

		try {
			ServerSocket serverSocket= new ServerSocket(8888);
			while(true){
				Socket socket = serverSocket.accept();
System.out.println("a client connected!");
				DataInputStream dInputStream = new DataInputStream(socket.getInputStream());
				String str = dInputStream.readUTF();
System.out.println(str);
				dInputStream.close();
			}
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


你可能感兴趣的:(Chat_7)