package Z0929;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.ScrollPane;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class QQk extends JFrame {
TextArea lishi;
JTextArea shuru;
JButton guanbi;
JButton fasong;
JPanel jp;
Socket c;
InputStream in;
OutputStream out;
Socket sk;
InputStream ski;
OutputStream sko;
boolean flag = false;
public QQk() {
setTitle("QQ聊天窗口");
setDefaultCloseOperation(2);
setSize(500, 450);
setLocationRelativeTo(null);
lishi = new TextArea();
shuru = new JTextArea();
guanbi = new JButton("关闭");
fasong = new JButton("发送");
jp = new JPanel();
JScrollPane lsdx = new JScrollPane(lishi);
lsdx.setPreferredSize(new Dimension(500, 250));
lishi.setBackground(Color.orange);
lishi.setEditable(false);
jp.setLayout(new FlowLayout(FlowLayout.RIGHT));
jp.add(guanbi);
jp.add(fasong);
add(lsdx, BorderLayout.NORTH);
add(shuru);
add(jp, BorderLayout.SOUTH);
guanbi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
flag = true;
QQk.this.dispose();
}
});
try {
c = new Socket("192.168.2.168", 9999);
out = c.getOutputStream();
in = c.getInputStream();
// sk=new Socket("192.168.2.234",9999);
// ski=sk.getInputStream();
// sko =sk.getOutputStream();
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
fasong.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Date d=new Date();
SimpleDateFormat si=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sd=si.format(d);
String message =3+" "+"许德生 "+sd+"\n"+ shuru.getText();
if(shuru.getText().trim().equals("")){
return;
}
try {
out.write(message.getBytes());
out.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
shuru.setText("");
}
});
new Thread(){
public void run() {
while(true){
String message="";
byte[] b=new byte[1024];
int i;
// int j;
try {
i = in.read(b);
message+=new String(b,0,i);
// byte[] b1=new byte[1024];
// j=ski.read(b1);
// message+=new String(b1,0,j);
} catch (IOException e) {
break;
}
String oldMessage=lishi.getText();
lishi.setText(oldMessage+"\n"+message);
// System.out.println(lishi.getText());
if(flag){
break;
}
}
}
}.start();
setVisible(true);
}
public static void main(String[] args) {
new QQk();
}
}
即时内部聊天程序——聊天界面
最新推荐文章于 2019-04-08 08:30:51 发布