该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
这是客户端的!!!
public class clientfram extends JFrame implements ActionListener{
Socket client = null;
JButton btnSend = new JButton("发送");
JButton btnExit = new JButton("退出");
JTextField txtInfo = new JTextField();
JTextArea txtChat = new JTextArea(4,8);
BufferedReader buf= null;
PrintStream out = null;
private boolean flag = false;
Runnable chat = null;
public clientfram(String winName) throws UnknownHostException, IOException{
this.LoginUI(winName);
this.AddActionListener();
}
private void AddActionListener() {
// TODO Auto-generated method stub
this.btnExit.addActionListener(this);
this.btnSend.addActionListener(this);
}
private void LoginUI(String winName){
// TODO Auto-generated method stub
this.setTitle(winName);
this.setBounds(400, 300, 400,400);
this.setLayout(new BorderLayout(20,30));
Panel p = new Panel(new GridLayout(1,2,30,30));
p.add(btnSend);
p.add(btnExit);
txtChat.setEditable(false);
txtChat.setLineWrap(true);
JScrollPane pane = new JScrollPane(txtChat);
this.add(pane,BorderLayout.CENTER);
this.add(txtInfo,BorderLayout.NORTH);
this.add(p,BorderLayout.SOUTH);
this.setResizable(false);
this.setVisible(true);
try {
client = new Socket("localhost",6666);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
txtChat.append("无法连接到服务器");
client = null;
return;
} catch (IOException e) {
// TODO Auto-generated catch block
txtChat.append("无法连接到服务器");
return;
}
try {
this.buf = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
this.out = new PrintStream(this.client.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
txtChat.append("已经连接上服务器:"+client.getInetAddress().getHostAddress());
flag = true;
chat = new Chat();
new Thread(chat).start();
}
class Chat implements Runnable{
// TODO Auto-generated method stub
public void run(){
while(flag){
try {
String str=buf.readLine();
txtChat.append("\r\n"+str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() instanceof JButton){
JButton btn = (JButton)e.getSource();
if(btn==this.btnExit){
try {
Action_Exit();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else{
try {
Action_Send();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
private void Action_Send() throws IOException {
// TODO Auto-generated method stub
out.print(txtInfo.getText());
txtChat.append("\r\n客户端说\r\n"+txtInfo.getText());
txtInfo.setText("");
}
private void Action_Exit() throws IOException {
// TODO Auto-generated method stub
flag = false;
if(client!=null){
out.print("bye");
out.close();
buf.close();
client.close();
}
System.exit(1);
}
}