java聊天源代码 java聊天程序设计代码( 三 )


}
}
else
{
JOptionPane.showMessageDialog(null,"发送信息失败!(服务器关闭/网络故障)","错误",JOptionPane.OK_OPTION);
}
}
/*-- 读取信息线程 --*/
class linread implements Runnable
{
public void run()
{
read();
}
public void read()
{
while(isConnected)
{
try {
String msg = in.readUTF();
if("SYSTEM_CLOSED".equals(msg))
{
JOptionPane.showMessageDialog(null,"读取消息失败(服务器关闭/网络故障)!","错误",JOptionPane.OK_OPTION);
isConnected = false;
}
else
allmsg.append(msg+"\n");
} catch (IOException e) {
}
}//end while
JOptionPane.showMessageDialog(null,"读取消息失败(服务器关闭/网络故障)!","错误",JOptionPane.OK_OPTION);
}//end read()
}
public void destory()
{
try {
this.out.close();
this.in.close();
this.s.close();
} catch (IOException e) {
}
this.dispose();
}
}
======================================================
package client;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class LoginFrame extends JFrame{
private JTextField name;
private JTextField ip;
private JButton ok,cancle;
public Socket socket;
public LoginFrame()
{
super("登录框");
this.setSize(400,80);
this.setLocation(100,100);
name = new JTextField("昵称");
ip = new JTextField("127.0.0.1");
ok = new JButton("登录");
cancle = new JButton("取消");
ok.addActionListener(new listenEvent());
cancle.addActionListener(new listenEvent());
//建立容器
addcomponettocontainer();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
/**
* 建立容器及控件
*/
public void addcomponettocontainer()
{
Container c = this.getContentPane();
c.setLayout(null);
name.setBounds(10,10,100,30);
ip.setBounds(120,10,100,30);
ok.setBounds(230,10,70,30);
cancle.setBounds(310,10,70,30);
c.add(name);
c.add(ip);
c.add(ok);
c.add(cancle);
this.setVisible(true);
this.setResizable(false);
}
public class listenEvent implements ActionListener
{
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
if(event.getSource()==ok)
{
String n = name.getText().trim();
String i = ip.getText().trim();
if("".equals(n)||"".equals(i))
{
JOptionPane.showMessageDialog(null,"昵称、IP不能够为空!","错误",JOptionPane.OK_OPTION);
}
else{login(n,i);}
}
if(event.getSource()==cancle)
{
name.setText("");
ip.setText("");
}
}
}
/**
* 进行登录
* @param name
* @param ip
*/
public void login(String name,String ip)
{
try {
socket = new Socket(ip,7777);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF(name);
out.flush();//强制输出缓存中的内容
//out.close();
new ClientFrame(name,socket);
destroywindow();
} catch (UnknownHostException e) {
JOptionPane.showMessageDialog(null,"找不到主机地址(IP错误/网络故障)!","错误",JOptionPane.OK_OPTION);
} catch (IOException e) {
}
}
public void destroywindow()
{
this.dispose();
}
public static void main(String[] args)
{
new LoginFrame();
}
}
==================================================
package server;
import java.awt.Container;
import java.awt.event.ActionEvent;

推荐阅读