Chat_7

来源:互联网 发布:java中文比较相似度 编辑:程序博客网 时间:2024/06/06 12:25
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(){@Overridepublic void windowClosing(WindowEvent e) {// TODO Auto-generated method stubSystem.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{@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString 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 blocke1.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();}}}


原创粉丝点击