package week6.serverAndClient;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
public class Client extends Thread {
public String message;
private Socket socket;
private DataOutputStream output;
private DataInputStream input;
private JTextArea allArea;
public Client(JTextArea allArea) {
this.allArea=allArea;
try {
socket = new Socket("localhost", 9000);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
try {
output = new DataOutputStream(socket.getOutputStream());
output.writeUTF("张三说:服务器你好!");
// 接受服务区信息
while (true) {
input = new DataInputStream(socket.getInputStream());
message = input.readUTF();
allArea.append(message);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("张三");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setBounds(100, 100, 738, 499);
frame.setResizable(false);
Container container = frame.getContentPane();
container.setLayout(null);
final JTextArea allArea = new JTextArea();// 总聊天框
allArea.setBounds(37, 20, 647, 275);
container.add(allArea);
final Client client = new Client(allArea);// 创建新连接
client.start();
final JTextField chartField = new JTextField();// 个人信息框
chartField.setBounds(37, 332, 534, 58);
container.add(chartField);
chartField.setColumns(10);
JButton sendBtn = new JButton("发送");// 发送按钮
sendBtn.setBounds(591, 332, 93, 23);
container.add(sendBtn);
sendBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String message = "
"+"张三说:" + chartField.getText();
chartField.setText(null);
allArea.append(message);
try {
client.output = new DataOutputStream(client.socket.getOutputStream());
client.output.writeUTF(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
JButton canelBtn = new JButton("取消");// 取消按钮
canelBtn.setBounds(592, 367, 93, 23);
container.add(canelBtn);
canelBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
chartField.setText(null);
}
});
}
}